First of all, I tried to look for some solution in this cool site. I have found a question relating to my issue, but my tests still fails. The question I found, can be found here: JUnit testing with simulated user input
Let's see my implementation:
I have an user interaction service class which read then validate the user inputs: UserInteractionService.java
package Services;
import java.util.Scanner;
public class UserInteractionService {
private static Scanner scanner = new Scanner(System.in);
public static int readIntegerAndValidate() {
while (!scanner.hasNextInt()) {
System.out.println("It is not a valid integer number. Try again!");
scanner.next();
}
return scanner.nextInt();
}
public static double readDoubleAndValidate() {
while (!scanner.hasNextDouble()) {
System.out.println("It is not a valid number. Try again!");
scanner.next();
}
return scanner.nextDouble();
}
}
And, of course, I have a test class for this service class: UserInteractionServiceTest.java
@Test
public void userWriteInput_checkIfItIsInteger_userTypedInteger() {
String inputData = "5";
System.setIn(new ByteArrayInputStream(inputData.getBytes()));
int input = readIntegerAndValidate();
assertEquals(5, input);
}
@Test
public void userWriteDouble_checkIfItIsDouble_userTypedDouble() {
String inputData = "5.3";
System.setIn(new ByteArrayInputStream(inputData.getBytes()));
double input = readDoubleAndValidate();
assertEquals(5.3, input, 0);
}
Well, my second test function (userWriteDouble_checkIfItIsDouble_userTypedDouble) fails, and I could not find the reason... As you can see I used the same pattern like in de first test. What is your opinion, why does this test fail? Shall I use some mocking framework (Mockito)? Thanks in advance for the answers!
Failure Trace:
java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Services.UserInteractionService.readDoubleAndValidate(UserInteractionService.java:21)
at Services.UserInteractionServiceTest.userWriteDouble_checkIfItIsDouble_userTypedDouble(UserInteractionServiceTest.java:23)
...