我必须测试别人无限运行但要求输入的方法:
public void automatize()
{
String cadena = new String();
while(true)
{
System.out.println("Executing...(Enter command)");
System.out.println("Enter Q to exit");
Scanner sc= new Scanner(new InputStreamReader(System.in));
cadena=sc.nextLine();
if(cadena.toLowerCase().equals("q"))
break;
String[] command = str.split(" ");
if(comando.length!=0)
new Extractor().run(command);
}
}
我该如何使用 JUnit 来测试它?
这是我尝试做的,但是,它实际上没有做任何事情:
@Test
public void testAutomatize_q() {
ByteArrayInputStream in = new ByteArrayInputStream("Q".getBytes());
System.setIn(in);
extractor.automatize();
System.setIn(System.in);
}
最佳答案
您可以通过调用 System.setIn(InputStream in) 将 System.in 替换为您自己的流。输入流可以是字节数组:
ByteArrayInputStream in = new ByteArrayInputStream("My string".getBytes());
System.setIn(in);
// do your thing
// optionally, reset System.in to its original
System.setIn(System.in)
不同的方法可以通过将 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/28765499/