Reputation: 1168
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?
Upvotes: 7
Views: 9847
Reputation: 24510
The System Rules library provides JUnit rules for such tests. Additionally you should use a parameterized test.
Upvotes: 0
Reputation: 141
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.
Upvotes: 9