简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM