0

I build an console application with lots of void methods and a Scanner. In the simple example: How can I mock a scanner to print to the console? Given console output "Do a" how can I respond via mock with "a"?

My test is failing - "Mockito cannot mock/spy because : final class".

Class to test

public class Class {
    Scanner scanner = new Scanner(new InputStreamReader(System.in));

    public void startScreen() {
        System.out.println("Do a");

        while (!scanner.hasNext("a")) {
            System.out.println("No valid option!");
            scanner.next();
        }
        String input;
        input = scanner.next();

        if(input.equals("a")){
            System.out.println("a");
        }
    }
}

Mock test

@Test
void test() {
    Scanner scanner = Mockito.mock(Scanner.class);
    Mockito.when(scanner.nextLine()).thenReturn("a");
    Class s = new Class();
    s.startScreen();
}
teres
  • 53
  • 6
  • This seems relevant to what you're trying to do: https://stackoverflow.com/questions/31635698/junit-testing-for-user-input-using-scanner –  Jul 27 '22 at 19:08
  • Indeed, I saw that. The relevant part where he tries to mock the scanner is commented with "Scanner cannot be mocked because the class is final." - https://stackoverflow.com/a/31635953/19255249. Not sure if there is a work around with mock. @JLCarveth – teres Jul 27 '22 at 19:14
  • Forget about mocking scanner, and simply replace the input stream as the top answer suggests. –  Jul 27 '22 at 19:24
  • Now I think how I can use this with Mockito, because I need to use Mockito. @JLCarveth – teres Jul 27 '22 at 19:47

0 Answers0