java - 使用模拟用户输入进行 JUnit 测试

标签 java eclipse junit user-input

我正在尝试为需要用户输入的方法创建一些 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/

相关文章:

java - 尝试创建数组列表的数组列表,但遇到此错误 :

java - JUnit 测试 : object not recreated between parameterized tests

java - 如何在某些 JUnit 测试之前调用设置方法

java - Mockito 依赖于先前调用的链接方法调用无法识别

python - 阿普塔纳;文件资源管理器中文件/文件夹名称前面的 ">"是什么意思?

java - 计算树中叶子的两种版本

java - java代码调用的cmd.exe在后台运行,如何使其显示为窗口?

java - 过滤的 API 在 elasticsearch 中被弃用

c++ - 无法打开文件c++

android - 在 Eclipse 模拟器上安装 Google Play