Using JUnit to test a main method that requires si

2019-02-20 20:37发布

问题:

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?

回答1:

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.



回答2:

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



标签: java input junit