控制台输入和输出的 JUnit 测试 [英] JUnit test for console input and output
问题描述
我只有一个方法 main.如何检查 System.out.println() 并将 Scanner 替换为使用 JUnit 自动输入值?
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);
}
}
推荐答案
理想情况下,提取笨拙的依赖项,以便您可以在没有它们的情况下进行测试.将 main
更改为简单的:
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
}
(考虑对 output
使用 Writer
而不是 PrintStream
.)
(Consider using a Writer
instead of a PrintStream
for output
.)
然后你真的不需要单元测试 main
- 但是你可以使用基于 的
,以及基于 Scanner
测试 doWork
StringReaderStringWriter
的输出,提供您想要的任何输入并检查输出.
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屋!