JUnit测试一个要求用户输入的方法

时间:2015-02-27 12:47:46

标签: java junit

我必须测试一些无休止地运行的elses方法,但要求输入:

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);
}

2 个答案:

答案 0 :(得分:2)

您可以通过调用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;
}

从这里采取:JUnit testing with simulated user input

答案 1 :(得分:1)

您可以使用像Mockito这样的框架来模拟Scanner对象,并在调用sc.nextLine()时返回修复值。 这是mockito http://mockito.org/的链接,请参阅'how'菜单以获得一些示例。