Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing console based applications/programs - Java

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

like image 339
name_masked Avatar asked Nov 19 '10 23:11

name_masked


People also ask

What is console based application in Java?

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.

How do I run a Java console application?

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.

Can JUnit be used for system testing?

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.


1 Answers

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. InputStreams should be reserved for raw byte-level processing.

like image 155
oxbow_lakes Avatar answered Sep 26 '22 08:09

oxbow_lakes