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