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

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

Check out another article in our installment on JUnit 4 Vs Junit 5.

Listing 8 The JUnit4CustomRuleTester class

JUnit4CustomRuleTester class.PNG

In listing 8, we use the previously defined CustomRule by doing the following:

  1. We declare a public CustomRule field and we annotate it with @Rule (1).
  2. We create the myCustomRuleTest method and annotate it with @Test (2).

The result of the execution of this test is shown in figure 1. The effective execution of the test is surrounded by the additional messages provided into the evaluate method of the CustomStatement class.

execution JUnit4CustomRuleTester.jpg
Figure 1 The result of the execution of JUnit4CustomRuleTester.

We now turn our attention to the JUnit 5 approach. JUnit 5 allows similar effects as in the case of the JUnit 4 rules by introducing the own extensions. The code is shorter and it relies on the declarative annotations style. We first define the CustomExtension class, which is used as an argument of the @ExtendWith annotation on the tested class.


Listing 9 The CustomExtension class

CustomExtension class.PNG

In listing 9 we do the following:

  1. We declare CustomExtension as implementing the AfterEachCallback and BeforeEachCallback interfaces (1’).
  2. We override the afterEach method, to be executed after each test method from the testing class which is extended with CustomExtension (2’).
  3. We override the beforeEach method, to be executed before each test method from the testing class is extended with CustomExtension (3’).


Interested in JUnit? Check out our trainings.


Catalin Tudose
Java and Web Technologies Expert



Still have questions?
Connect with us