-1

I need to test a method that asks the user for an input and charges the player the inputted amount. The method to be tested:

public void askForBetSize() {
    System.out.println("\nYour stack: " + player.getBalance());
    System.out.print("Place your bet: ");
    bet = Integer.parseInt(keyboard.nextLine()); // = this needs to be simulated
    player.charge(bet);
}

Current unit test is:

@Test 
public void bettingChargesPlayerRight() {
    round.setCards();
    round.askForBetSize(); // here I would like to simulate a bet size of 100
    assertEquals(900, round.getPlayer().getBalance()); // default balance is 1000
}

I tried to implement this and this but after testing previous classes the test stopped running when it started to test this method.

Community
  • 1
  • 1
flowjow
  • 171
  • 1
  • 3
  • 14

2 Answers2

1

What you need is a test double, in particular a Mock or a Stub. Since you do not want to use Mockito you probably should use your own Stub implementation instead. A Stub is an object that always returns the same canned response.

My solution (and as it probably has been mentioned elsewhere) would be to refactor your code so that you can pass in the test double to the class under test.

In my example I have created an interface to represent the user's answer and which declares your nextLine() method. The real object would use the System.in to capture the user response.

Instead for the test I create an instance of this type as an anonymous inner class, to provide the canned answer required.

public interface PlayerInput {

    String nextLine();

}


public class SimulateSystemInTest {

    private Round round;

    private PlayerInput keyboardStub = new PlayerInput() {

                                        private String bet = "100";

                                        @Override
                                        public String nextLine() {
                                            System.out.println(bet);
                                            return bet;
                                        }
                                    };

    @Before
    public void setUp() {
        round = new Round(new Player(), keyboardStub);
    }

    @Test
    public void bettingChargesPlayerRight() {
        round.setCards();
        round.askForBetSize(); // here I would like to simulate a bet size of 100
        assertEquals(900, round.getPlayer().getBalance()); // default balance is 1000
    }

}
0

See Mockito (stubs and mock), It will help you.Mockito

EK.
  • 2,890
  • 9
  • 36
  • 49