我正在尝试为需要用户输入的方法创建一些 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;
}
有没有可能的方法来自动向程序传递一个 int 而不是我或其他人在 JUnit 测试方法中手动执行此操作?喜欢模拟用户输入吗?
最佳答案
您可以替换 System.in with you own stream by calling System.setIn(InputStream in) 。 InputStream 可以是字节数组:
InputStream sysInBackup = System.in; // backup System.in to restore it later
ByteArrayInputStream in = new ByteArrayInputStream("My string".getBytes());
System.setIn(in);
// do your thing
// optionally, reset System.in to its original
System.setIn(sysInBackup);
不同的方法可以通过将 IN 和 OUT 作为参数传递来使该方法更具可测试性:
public static int testUserInput(InputStream in,PrintStream out) {
Scanner keyboard = new Scanner(in);
out.println("Give a number between 1 and 10");
int input = keyboard.nextInt();
while (input < 1 || input > 10) {
out.println("Wrong number, try again.");
input = keyboard.nextInt();
}
return input;
}
关于java - 使用模拟用户输入进行 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986373/