0

I'm writing a console application in Java that gets input from the user by 'Scanner' class. I don't want to enter each time that I test my program the input manually in the console, so I want to put all my inputs in a text file and make the Java program read this text file instead of typing again the inputs.

The way I found to do it is changing the line:

Scanner sc = new Scanner(System.in);

to:

Scanner sc = new Scanner(new File(path_to_text_file));

Can you recommend another way that doesn't involve changing the code?

2 Answers 2

1

Since you want to have this for testing, the best way would be to write a test for this class. Have a look at JUnit.

In such a test you could provide a different Scanner to you original class, either by using

Scanner sc = new Scanner(new File(path_to_text_file));

or you could use a framework like Mockito in order to fake different user inputs through Scanner and then check whether these inputs produced the correct outputs.

1

If you absolutely can't change your code, use System.setIn to replace the default input stream with one of your choosing.

Be sure always to change the stream back to the original one once you've finished testing - in doing this, you're mutating global state, so you can leave things in a bad state for the rest of your tests.

InputStream previousIn = System.in;
InputStream replacement = new FileInputStream(path_to_text_file);
System.setIn(replacement);
try {
  // ... Do your testing.
} finally {
  System.setIn(previousIn);
}

Or, change the design of your code so that you inject the input stream that you depend on. This avoids the mutation of global state, which is a good thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.