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:

dynamic-tests-junit5

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

Leave a Comment

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close