user-icon Stefan Ludwig
27. October 2016
timer-icon 3 min

Better Test Structure with JUnit 5

Structuring your tests in an understandable way is not an easy task. JUnit 5 can help you create a sensible test structure by grouping related tests together. In this post I will demonstrate this on a rather simple example. So lets start at the beginning.

The Class Under Test

To demonstrate a well structured test, lets first define a relatively simple class to test: Title
Here are some functional properties of the Title class:

  • It is a value object.
  • Wraps a String value.
  • Value can’t be NULL, empty, or otherwise ‘blank’.
  • Values are automatically trimmed.
  • Equality is based on the wrapped value.
  • Instances can only be created using the factory method.

The Test

Now lets create some tests for the Title class. The following tests follow a simple set of rules:

  1. Each test needs a readable name stating the property it is testing. This is achieved by making use of the great new @DisplayName annotation.
  2. If a property of the class under test can’t be tested with a single test, multiple tests are grouped together. This is done within an inner class annotated with @Nested. This will not only group them structurally within your test class, but also in the result view when executing them.
  3. Grouped tests state what makes them special (what they are testing) without repeating the statement of the class they are located in.

The Result

When executed the above test will create the following result:


As you can see this approach can help you make sense, not only within your code, but also when looking at test results. Among other things, it makes it very easy to see if any relevant test is missing. You can check out the example’s code on GitHub.

In order to run the tests, you’ll need two things:

  1. IntelliJ IDE, since Eclipse does not support JUnit 5 (yet)
  2. The Project Lombok plugin in order to process the class under test’s annotations.

Comment article