All,
I have written a PhoneBook application in Java that is command line based. The application basically asks for some details of user like Name, Age, Address and phone numbers and stores them in a file. Other operations involve looking up PhoneBook by name, phone number etc. All the details are entered through console.
I am trying to write JUnit test cases for each of the functionalities that I have implemented but not able to figure out how to redirect System.in
in the implementation code to something in my JUnit test methods that would supply those values when my actual code stops for user input?
Example:
My implementation code has:
BufferedReader is = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Please enter your name:");
String name = is.readLine(); // My test cases stop at this line. How can I pass command line values i.e. redirect System.in to my test based values?
Hope it makes sense
The Java Console class is be used to get input from console. It provides methods to read texts and passwords. If you read password using Console class, it will not be displayed to the user. The java.
Open the Eclipse console (Window -> Show View -> Console), and run this program. You should see hello world in the console. That console returns a null in eclipse for me.
JUnit can be used as a test runner for any kind of test: e.g. system and integration tests; tests which are interacting with a deployed application. E.g. the WebDriver tests here all use JUnit, and they interact with an application which runs in a browser.
Why not write your application to take a Reader
as input? That way, you can easily replace an InputStreamReader(System.in)
with a FileReader(testFile)
public class Processor {
void processInput(Reader r){ ... }
}
And then two instances:
Processor live = new Processor(new InputStreamReader(System.in));
Processor test = new Processor(new FileReader("C:/tmp/tests.txt");
Getting used to coding to an interface will bring great benefits in almost every aspect of your programs!
Note also that a Reader
is the idiomatic way to process character-based input in Java programs. InputStream
s should be reserved for raw byte-level processing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With