Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

command line - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...