Dynamic Tests with JUnit 5
The Class Under Test
For starters, let’s define a simple class to be tested: Calculator
This class offers two methods:
- adding two integers
- subtracting two integers
1 2 3 4 5 6 7 8 9 10 11 |
public class Calculator { public int add(int a, int b){ return a + b; } public int subtract(int a, int b){ return a - b; } } |
The Rules
Next we define a set of rules in two separate files. These will provide the input for our dynamic tests.
1 2 3 4 5 6 7 8 |
addition-rules.txt 0, 0 | 0 0, 1 | 1 1, 0 | 1 -1, 0 |-1 0,-1 |-1 -1, 1 | 0 -1,-1 |-2 |
1 2 3 4 5 6 7 8 |
subtraction-rules.txt 0, 0 | 0 0, 1 |-1 1, 0 | 1 -1, 0 |-1 0,-1 | 1 -1, 1 |-2 -1,-1 | 0 |
Both files use the same format: Two input variables and an expected result.
The Tests
Finally we write our tests. The rule files are parsed by a class called DataSet
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
public class CalculatorTest { Calculator cut = new Calculator(); @TestFactory Stream<DynamicTest> addition() { return DataSet.parseRuleFile("addition-rules.txt") .map(dataSet -> dynamicTest(getAdditionDisplayName(dataSet), () -> { int result = cut.add(dataSet.getValueA(), dataSet.getValueB()); assertThat(result).isEqualTo(dataSet.getExpectedResult()); })); } String getAdditionDisplayName(DataSet dataSet) { return dataSet.getValueA() + " + " + dataSet.getValueB() + " = " + dataSet.getExpectedResult(); } @TestFactory Stream<DynamicTest> subtraction() { return DataSet.parseRuleFile("subtraction-rules.txt") .map(dataSet -> dynamicTest(getSubtractionDisplayName(dataSet), () -> { int result = cut.subtract(dataSet.getValueA(), dataSet.getValueB()); assertThat(result).isEqualTo(dataSet.getExpectedResult()); })); } String getSubtractionDisplayName(DataSet dataSet) { return dataSet.getValueA() + " - " + dataSet.getValueB() + " = " + dataSet.getExpectedResult(); } } |
The Result
When we execute the test class within IntelliJ, we get the following result:
As you can see, JUnit generated tests using our test factories based on the input from the rule files.
This example is of course rather simple. But I think it still shows what kinds of tests are possible with JUnit 5.
You can check out the example’s code on GitHub.
In order to run the tests, you’ll need a current version of IntelliJ, since Eclipse does not support JUnit 5 (yet).
Recent posts






Comment article