Home > Enterprise >  How can I pass value to a method which doesnt have parameters?
How can I pass value to a method which doesnt have parameters?

Time:05-20

I have a method

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

and I wonder if I can unit-test it if it actually creates the user. However it doesnt have 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 arguements with scanner, what I cant do under testing obviously. Other logics were tried aswell. 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?

CodePudding user response:

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);
  • Related