【问题标题】:JUnit test a method that asks for user inputJUnit 测试一个要求用户输入的方法
【发布时间】:2015-04-30 04:34:13
【问题描述】:

我必须测试别人无休止地运行但要求输入的方法:

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

【问题讨论】:

    标签: java junit


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您可以使用 Mockito 之类的框架来模拟 Scanner 对象,并在调用 sc.nextLine() 时返回一个固定值。 这是 mockito http://mockito.org/ 的链接,请参阅“如何”菜单以获取一些示例。

      【讨论】:

        猜你喜欢
        • 2014-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-18
        • 1970-01-01
        • 1970-01-01
        • 2019-11-27
        相关资源
        最近更新 更多