Using JUnit to test a main method that requires si

2019-02-20 20:28发布

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

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 |
+-------+-----------------+

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

标签: java input junit
2条回答
小情绪 Triste *
2楼-- · 2019-02-20 20:54

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.

查看更多
等我变得足够好
3楼-- · 2019-02-20 21:14

The System Rules library provides JUnit rules for such tests. Additionally you should use a parameterized test.

查看更多
登录 后发表回答