使用 JUnit 测试需要使用输入流模拟键盘输入的主要方法?
Using JUnit to test a main method that requires simulation of keyboard input with an input stream?
假设我有一个程序,其主要方法使用 java.util.Scanner
class 来接收用户输入。
import java.util.Scanner;
public class Main {
static int fooValue = 0;
public static void main(String[] args) {
System.out.println("Please enter a valid integer value.");
fooValue = new Scanner(System.in).nextInt();
System.out.println(fooValue + 5);
}
}
这个程序所做的就是接收一个整数输入,并输出一个整数加 5。这意味着我可以想出一个 table 像这样:
+-------+-----------------+
| Input | Expected output |
+-------+-----------------+
| 2 | 7 |
| 3 | 8 |
| 5 | 12 |
| 7 | 13 |
| 11 | 16 |
+-------+-----------------+
我需要对这组输入数据进行 JUnit 测试。解决这样的问题最简单的方法是什么?
您可以像这样重定向 System.out、System.in 和 System.err:
System.setOut(new PrintStream(new FileOutputStream("output")));
System.setErr(new PrintStream(new FileOutputStream("error")));
System.setIn(new FileInputStream("input"));
所以在你的单元测试中你可以设置这个重定向和运行你的class。
System Rules 库为此类测试提供了 JUnit 规则。此外,您应该使用参数化测试。
假设我有一个程序,其主要方法使用 java.util.Scanner
class 来接收用户输入。
import java.util.Scanner;
public class Main {
static int fooValue = 0;
public static void main(String[] args) {
System.out.println("Please enter a valid integer value.");
fooValue = new Scanner(System.in).nextInt();
System.out.println(fooValue + 5);
}
}
这个程序所做的就是接收一个整数输入,并输出一个整数加 5。这意味着我可以想出一个 table 像这样:
+-------+-----------------+
| Input | Expected output |
+-------+-----------------+
| 2 | 7 |
| 3 | 8 |
| 5 | 12 |
| 7 | 13 |
| 11 | 16 |
+-------+-----------------+
我需要对这组输入数据进行 JUnit 测试。解决这样的问题最简单的方法是什么?
您可以像这样重定向 System.out、System.in 和 System.err:
System.setOut(new PrintStream(new FileOutputStream("output")));
System.setErr(new PrintStream(new FileOutputStream("error")));
System.setIn(new FileInputStream("input"));
所以在你的单元测试中你可以设置这个重定向和运行你的class。
System Rules 库为此类测试提供了 JUnit 规则。此外,您应该使用参数化测试。