Reputation: 15
I came up with a problem while trying to write a JUnit test for one specific method. I searched for possible solutions but many of them were not helpful as the output was not dependent on the input. Any help would be much appreciated.
My class method looks like this:
public static void method1() {
Scanner input = new Scanner(System.in);
String state = input.nextLine();
if( /* condition dependent on state value */ ) {
System.out.println("...");
} else {
System.out.println("..."+state+"...");
}
}
How to write a JUnit test for it, can Robot class somehow solve the problem?
Upvotes: 0
Views: 183
Reputation: 19968
You can manipulate System.in
and System.out
using System.setIn()
etc. For instance
System.setIn(new ByteArrayInputStream("test data".getBytes()));
However, I have the feeling that for your case, changing your method in a way that @p-j-meisch suggested in https://stackoverflow.com/a/59513668/2621917 is much better.
Upvotes: 1
Reputation: 19421
If you extract the logic to a separate function like
public static void method1() {
Scanner input = new Scanner(System.in);
String state = input.nextLine();
System.out.println(processingLogic(state));
}
static String processingLogic(String state) {
if ( /* condition dependent on state value */) {
return "some value";
} else {
return "some other value";
}
}
you can write a unit test for that function to see that it works correctly.
Upvotes: 3