使用模拟用户输入进行 JUnit 测试 [英] JUnit testing with simulated user input

查看:34
本文介绍了使用模拟用户输入进行 JUnit 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为需要用户输入的方法创建一些 JUnit 测试.被测方法看起来有点像下面的方法:

I am trying to create some JUnit tests for a method that requires user input. The method under test looks somewhat like the following method:

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 测试方法中手动执行此操作?喜欢模拟用户输入?

Is there a possible way to automatically pass the program an int instead of me or someone else doing this manually in the JUnit test method? Like simulating the user input?

提前致谢.

推荐答案

可以替换 System.in 通过调用 System.setIn(InputStream in) 使用您自己的流.InputStream 可以是一个字节数组:

You can replace System.in with you own stream by calling System.setIn(InputStream in). InputStream can be a byte array:

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 作为参数传递,不同的方法可以使此方法更易于测试:

Different approach can be make this method more testable by passing IN and OUT as parameters:

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 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆