可能重复:
Java, Junit - Capture the standard input / Output for use in a unit test
JUnit test for System.out.println()
我编写了一段代码,类似于下面的代码。我想对这个方法进行单元测试,现在我被困在了System.out部分。假设用户输入为12,这将提示用户使用“错误的号码,再试一次”。测试这个输出是可能的,还是使用JUnit是不可能的?
public static int testUserInput() {
Scanner keyboard = new Scanner(System.in);
System.out.println("Give a number between 1 and 10");
int input = keyboard.nextInt();
while (input < 1 || input > 10) {
System.out.println("Wrong number, try again.");
input = keyboard.nextInt();
}
return input;
}提前谢谢。
发布于 2011-06-20 21:46:18
System.out是java.io.PrintStream型的。如果您可以模拟或传递另一种类型的PrintStream,可以将输出捕获到StringReader中,则可以断言其值。
https://stackoverflow.com/questions/6417919
复制相似问题