使用JUnit测试需要使用输入流模拟键盘输入的主方法?
问题描述:
假设我有一个带有main方法的程序,该方法使用 java.util.Scanner
类来接收用户输入。
Let's suppose I have a program with a main method that uses the java.util.Scanner
class to receive user input.
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.这意味着我能够得到一个这样的表:
All this program does is receive an integer input, and output an integer plus 5. Which means I'm able to come up with a table like this:
+-------+-----------------+
| Input | Expected output |
+-------+-----------------+
| 2 | 7 |
| 3 | 8 |
| 5 | 12 |
| 7 | 13 |
| 11 | 16 |
+-------+-----------------+
我需要对这组输入数据进行JUnit测试。接近这样的问题最容易的是什么?
I need to make a JUnit test for this set of input data. What's the easiest of approaching a problem like this?
答
您可以重定向System.out,System.in和System.err像这样:
You can redirect System.out, System.in, and System.err like this:
System.setOut(new PrintStream(new FileOutputStream("output")));
System.setErr(new PrintStream(new FileOutputStream("error")));
System.setIn(new FileInputStream("input"));
因此,在单元测试中,您可以设置此重定向并运行您的课程。
So in you unit test you can setup this redirection and run your class.