user-icon Stefan Ludwig
03. November 2016
timer-icon 2 min

Dynamic Tests with JUnit 5

Sometimes there are a lot of relevant cases to be tested for a single method. In these instances it is rather tedious to implement an unique test method for each relevant case. JUnit 5 can help you with the introduction of dynamic tests.

The Class Under Test

For starters, let’s define a simple class to be tested: Calculator
This class offers two methods:

  1. adding two integers
  2. subtracting two integers

The Rules

Next we define a set of rules in two separate files. These will provide the input for our dynamic tests.

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.

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).

Comment article