How can I test against console input automaticly by mocking?

Mangos :

When trying to mock console input, the test doesen't behave as i expected

I created a wrapper class for console input, output, and tried mocking its behaviour

public class ConsoleReaderWriter {

public void printLine(String message) {

    System.out.println(message);
}

public String readLine() {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    String result = "";
    try {
        result = bufferedReader.readLine();
    } catch (IOException e) {
        System.err.print(e);
    }
    return result;

}

}

//the method to be tested

public String readPlayerName() {
    consoleReaderWriter.printLine("> What is your name?");
    String playerName = consoleReaderWriter.readLine();
    return playerName;
}

//my test attempt

@Test
public void testReadPlayerNameShouldReturnNameString() {
    String testName = "John Doe";

    ConsoleReaderWriter testReaderWriter = mock(ConsoleReaderWriter.class);

    when(testReaderWriter.readLine()).thenReturn("John Doe");

    assertEquals(testName, underTest.readPlayerName());
}

I am using Mockito. When i run the test, it prompts me to enter input from the console. The test passes, if i enter the expected name, however, i would like to make it automatic, so that i dont have to enter any input while the test runs. Thanks in advance.

Peteef :

Please take a look at the example:

@RunWith(MockitoJUnitRunner.class)
public class TestClass {
   @Mock
   ConsoleReaderWriter crw;

   @InjectMocks
   UnderTestClass underTest;

   //Some other fields

   @Test
   public void testReadPlayerNameShouldReturnNameString() {
      String testName = "John Doe";

      when(crw.readLine()).thenReturn("John Doe");

      assertEquals(testName, underTest.readPlayerName());
   }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117078&siteId=1