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

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

问题描述

全部,

我用 Java 编写了一个基于命令行的电话簿应用程序.该应用程序基本上会询问用户的一些详细信息,例如姓名、年龄、地址和电话号码,并将它们存储在一个文件中.其他操作包括通过姓名、电话号码等查找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 作为输入?这样,您可以轻松地将 InputStreamReader(System.in) 替换为 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");

习惯于对界面进行编码将为您程序的几乎每个方面带来巨大的好处!

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

另请注意,Reader 在 Java 程序中处理基于字符的输入的惯用方式.InputStreams 应保留用于原始字节级处理.

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天全站免登陆