java - JUnit 测试要求用户输入的方法

标签 java junit

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

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

取自这里:JUnit testing with simulated user input

关于java - JUnit 测试要求用户输入的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28765499/

相关文章:

java - 向 Guice 模块添加新绑定(bind)?

java - 带有卡尺的 Junit 设置

java - Maven 构建正在运行,但 junit 抛出 NoSuchMethodError

java - Spring Boot Junit测试通过构造函数注入(inject)注入(inject)dao接口(interface)

java - 装饰设计和工厂设计模式

java - 如何使用 Apache HTTP 组件为每个路由配置 SSLSocket 工厂

java - 如何让 Guice 将带注释的注入(inject)绑定(bind)到单个实例

java - 出现错误匹配器异常的无效用户

java - 我应该如何为子类编写单元测试?

java - 如何避免在包含的 JSP 文件中重新声明标签库?