测试基于控制台的应用程序/程序 - Java [英] Testing console based applications/programs - Java

查看:308
本文介绍了测试基于控制台的应用程序/程序 - Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部,

我用Java编写了一个基于命令行的PhoneBook应用程序。该应用程序基本上要求一些用户的详细信息,如姓名,年龄,地址和电话号码,并将它们存储在一个文件中。其他操作涉及通过名称,电话号码等查找PhoneBook。所有详细信息通过控制台输入。

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.

我试图为每个功能编写JUnit测试用例我已经实现,但不能找出如何重定向 System.in 在实现代码中的东西在我的JUnit测试方法,将提供这些值,当我的实际代码停止用户输入?

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?

示例:

我的实现代码有:

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?

希望有意义

推荐答案

为什么不写你的应用程序以 Reader 作为输入?这样,您可以轻松地用 FileReader(testFile)

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){ ... }
}

然后两个实例:

Processor live = new Processor(new InputStreamReader(System.in));
Processor test = new Processor(new FileReader("C:/tmp/tests.txt");


$ b

Getting used to coding to an interface will bring great benefits in almost every aspect of your programs!

注意,一个 Reader

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.

这篇关于测试基于控制台的应用程序/程序 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆