【发布时间】:2014-01-22 22:36:56
【问题描述】:
理想情况下,我想编写 JUnit 测试代码,以交互方式测试学生基于文本的 I/O 应用程序。使用System.setIn()/.setOut() 会导致问题,因为底层流是阻塞的。 Birkner 的系统规则 (http://www.stefan-birkner.de/system-rules/index.html) 在较早的帖子 (Testing console based applications/programs - Java) 中被推荐,但它似乎要求在运行单元测试目标之前提供所有标准输入,因此不是交互式的。
要提供一个具体的测试目标示例,请考虑以下猜谜游戏代码:
public static void guessingGame() {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int secret = random.nextInt(100) + 1;
System.out.println("I'm thinking of a number from 1 to 100.");
int guess = 0;
while (guess != secret) {
System.out.print("Your guess? ");
guess = scanner.nextInt();
final String[] responses = {"Higher.", "Correct!", "Lower."};
System.out.println(responses[1 + new Integer(guess).compareTo(secret)]);
}
}
现在想象一个 JUnit 测试,它将提供猜测、阅读响应并完成游戏。如何在 JUnit 测试框架中实现这一点?
回答:
使用下面Andrew Charneski推荐的方法,添加输出刷新(包括在上面每个打印语句后添加System.out.flush();),非随机播放,恢复System.in/out,这段代码似乎执行了我的测试正在想象:
@Test
public void guessingGameTest() {
final InputStream consoleInput = System.in;
final PrintStream consoleOutput = System.out;
try {
final PipedOutputStream testInput = new PipedOutputStream();
final PipedOutputStream out = new PipedOutputStream();
final PipedInputStream testOutput = new PipedInputStream(out);
System.setIn(new PipedInputStream(testInput));
System.setOut(new PrintStream(out));
new Thread(new Runnable() {
@Override
public void run() {
try {
PrintStream testPrint = new PrintStream(testInput);
BufferedReader testReader = new BufferedReader(
new InputStreamReader(testOutput));
assertEquals("I'm thinking of a number from 1 to 100.", testReader.readLine());
int low = 1, high = 100;
while (true) {
if (low > high)
fail(String.format("guessingGame: Feedback indicates a secret number > %d and < %d.", low, high));
int mid = (low + high) / 2;
testPrint.println(mid);
testPrint.flush();
System.err.println(mid);
String feedback = testReader.readLine();
if (feedback.equals("Your guess? Higher."))
low = mid + 1;
else if (feedback.equals("Your guess? Lower."))
high = mid - 1;
else if (feedback.equals("Your guess? Correct!"))
break;
else
fail("Unrecognized feedback: " + feedback);
}
} catch (IOException e) {
e.printStackTrace(consoleOutput);
}
}
}).start();
Sample.guessingGame();
}
catch (IOException e) {
e.printStackTrace();
fail(e.getMessage());
}
System.setIn(consoleInput);
System.setOut(consoleOutput);
}
【问题讨论】:
-
你的意思是像Sikuli这样的东西吗?
-
Sikuli 似乎面向图形用户界面,而我专注于基于文本的 I/O。不过,感谢您的链接。我会把它藏起来改天。
标签: java unit-testing junit