Migrating from JUnit 4 to JUnit 5: replacing rules with the extension model. Part 3

Migrating from JUnit 4 to JUnit 5: replacing rules with the extension model. Part 3

In the third part of our article on JUnit we look at how we test with custom rules and extensions.
In the third part of our article on JUnit we look at how we test with custom rules and extensions.


4. Testing with custom rules and extensions

We move our attention to replacing the custom rules. Using the own rules for the tests is particularly useful when some types of tests need similar additional actions before and after their execution.
For this demonstration, we have created our own classes which implement the TestRule interface. To do this, one has to override the apply(Statement, Description) method which returns an instance of Statement. Such an object represents the tests within the JUnit runtime and Statement#evaluate()runs them. The Description object describes the individual test. We can use it to read information about the test through reflection.

Listing 6 The CustomRule class


CustomRule class JUnit.PNG

To clearly show how to define our own rules, we look at listing 6, where we do the following:

  1. We declare our CustomRule class that implements the TestRule interface (1).
  2. We keep references to a Statement field and to a Description field (2) and we use them into the apply method that returns a CustomStatement (3).

Listing 7 The CustomStatement class


CustomStatement class JUnit.PNG

In listing 7, we do the following:

  1. We declare our CustomStatement class that extends the Statement class (1).
  2. We keep references to a Statement field and to a Description field (2) and we use them as arguments of the constructor (3).
  3. We override the inherited evaluate method and call base.evaluate() inside it (4).

Interested in JUnit? Check out our trainings.


Catalin Tudose
Java and Web Technologies Expert
Mai ai întrebări?
Conectați-văcu noi