使用JUnit测试需要使用输入流模拟键盘输入的主方法? [英] Using JUnit to test a main method that requires simulation of keyboard input with an input stream?

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

问题描述

假设我有一个带有main方法的程序,该方法使用 java.util.Scanner 类来接收用户输入。

Let's suppose I have a program with a main method that uses the java.util.Scanner class to receive user input.

import java.util.Scanner;

public class Main {
    static int fooValue = 0;

    public static void main(String[] args) {
        System.out.println("Please enter a valid integer value.");
        fooValue = new Scanner(System.in).nextInt();
        System.out.println(fooValue + 5);
    }
}

所有这个程序都接收整数输入,并且输出一个整数加5.这意味着我能够得到一个这样的表:

All this program does is receive an integer input, and output an integer plus 5. Which means I'm able to come up with a table like this:

+-------+-----------------+
| Input | Expected output |
+-------+-----------------+
|     2 |               7 |
|     3 |               8 |
|     5 |              12 |
|     7 |              13 |
|    11 |              16 |
+-------+-----------------+

我需要对这组输入数据进行JUnit测试。接近这样的问题最容易的是什么?

I need to make a JUnit test for this set of input data. What's the easiest of approaching a problem like this?

推荐答案

您可以重定向System.out,System.in和System.err像这样:

You can redirect System.out, System.in, and System.err like this:

System.setOut(new PrintStream(new FileOutputStream("output")));

System.setErr(new PrintStream(new FileOutputStream("error")));

System.setIn(new FileInputStream("input"));

因此,在单元测试中,您可以设置此重定向并运行您的课程。

So in you unit test you can setup this redirection and run your class.

这篇关于使用JUnit测试需要使用输入流模拟键盘输入的主方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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