JUnit测试控制台输入和输出 [英] JUnit test for console input and output
问题描述
我只有一个方法main。如何检查System.out.println()并使用JUnit自动替换Scanner到输入值?
I have only one method main. How to check System.out.println() and replace Scanner to input values automatically using JUnit?
请提供一些解决方案...
P.S. Please, provide some solutions...
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[4];
for (int i = 0; i < arr.length; i++) {
arr[i] = scanner.nextInt();
}
for (int i = 0; i < arr.length; i++) {
int res = 0;
int k = 0;
int num = arr[i];
/*.....*/
System.out.println(num);
}
}
推荐答案
,提取尴尬的依赖关系,让你可以测试没有他们。将主
变更为:
Ideally, extract the awkward dependencies so that you can test without them. Change main
to simply:
public static void main(String[] args) {
doWork(new Scanner(System.in), System.out);
}
// TODO: Rename to something meaningful
public static void doWork(Scanner input, PrintStream output) {
// Remainder of code
}
(考虑使用 Writer
a PrintStream c)。
(Consider using a Writer
instead of a PrintStream
for output
.)
真的需要单元测试 main
- 但你可以使用扫描器测试
doWork
/ code>,基于 StringReader
,并输出基于 StringWriter
,提供您想要的任何输入,检查输出。
Then you don't really need to unit test main
- but you can test doWork
using a Scanner
based on a StringReader
, and output based on a StringWriter
, providing whatever input you want and checking the output.
这篇关于JUnit测试控制台输入和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!