I need to test a method (i.e. also the methods that are called by him) with JUnit. The problem is that the "parent" method requires user's input from keyboard in the middle of the code lines: the input doesn't get passed to other methods, but is handled in the same method that is running and getting tested.
I know I could be using
String input = "sampleString";
InputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
assertEquals(sampleString, Obj.inputReader("sampleString"));
but as far as I know this can't be done since if the code is the following:
public class MyClass{
public int readInt() {
Scanner scan = new Scanner(System.in);
System.out.print("Enter number: ");
int num = scan.nextInt();
scan.close();
return num;
}
}
@Test
public void testmethod() throws IOException {
MyClass myclass = new Myclass();
myclass.readInt();
String input = "4";
InputStream in = new ByteArrayInputStream(input.getBytes());
System.setIn(in);
assertEquals(4, Obj.inputReader(parseToInt("4")));
the test keeps running since no keyboard input is received and it's impossible to reach the following line.
Does anybody know a method or suggest a path to get it done?
Thanks in advance to everybody!