javaunit-testingmockito

How can I pass value to a method which doesn't have parameters?


I have this method:

  public User authenticateUser() {
      Scanner scr = new Scannery(System.in);
      String name = scr.nextLine();
      String password = scr.nextLine();
      return new User(name, password);
  }

and I wonder if I can unit-test it if it actually creates the user. However it doesn't have any parameters.

I tried the following:

@Test
public void testIfReadCredentialsReturnUser() {
    User user = mock(User.class);
    ConsoleView view = new ConsoleView();
    view.readCredentials().setEmail("asd.com");
    view.readCredentials().setPassword("asd");
    assertNotNull(view.readCredentials());
}

This however actually makes me pass the arguments with scanner, what I cant do under testing obviously.

Other logic were tried as well. I also tried using when(), thenReturn(), thenAnswer(), but I couldn't find a way to solve this, as I'm fairly new to mocking.

Can somebody share some ideas with me please?


Solution

  • Here's is what you can do:

    String data = "TestName\nTestPW\n";
    InputStream testInput = new ByteArrayInputStream(data.getBytes() );
    InputStream old = System.in;
    System.setIn(testInput);
    user = authenticateUser();
    System.setIn(old);