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

查看:336
本文介绍了用模拟用户输入进行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)
输入流可以是字节数组:

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

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作为参数,不同的方法可以使此方法更具可测性:

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天全站免登陆