Reputation: 397
I have got a static
method which uses a static final
Scanner
to get user input from the console.
When testing I would like to create a number of tests with different input (obviously). This works fine, as long as the tests are run individually. Running the whole class does not work, because (apparently) the Scanner is already initialized with the input from the previous test, which does not have any more lines than required for the first test.
The specific error I am getting is:
java.util.NoSuchElementException: No line found
Here some code for clarification:
public class UserInputHandler {
public static final Scanner SCANNER = new Scanner(System.in);
}
The class I am trying to test (and a few others) is using above Scanner
to query the user.
My test:
InputStream in = new ByteArrayInputStream("test".getBytes());
System.setIn(in);
TestClass testclass = new TestClass();
testClass.method(); // Scanner is used in this method
How can I get my tests to work for more than one TestClass instance?
Upvotes: 1
Views: 528
Reputation: 140417
The real issue is here:
public class UserInputHandler {
public static final Scanner SCANNER = new Scanner(System.in);
}
You are forcing that input to come from System.in
. Why not use
public class UserInputHandler {
public Scanner getScanner() {
return new Scanner(someInputStream);
Of course, now you have to worry where that someInputStream
is coming from, but: you enabled yourself to be much more flexible.
Your code doesn't really on a single static object, instead it makes a call and receives that reads from somewhere. And then, in your tests, you simply define input streams, and you make sure that these input streams can be used (for example by making that a field of the UserInputHandler class that gets set when instantiating that class.
In other words: the real solution is to change your production code to make it A) more flexible and B) easy to test. You got it backwards: you wrote inflexible and hard to test code, and now you try to bend your test cases to be reasonable.
Wrong approach: when you can't write simple, straight forwards tests, then your production code needs to be reworked. Always.
Upvotes: 4