'Y'

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




Share the knowledge

Luxoft Warsaw - Warsaw Spire, plac Europejski 1, 00-844 Warszawa
Dimitrie Pompeiu nr 5-7 , building C, Et. 5, sect 2, Bucharest, 014459

Contact phone:

021 371 4858
Luxoft Poland Wroclaw - Silver Tower pl. Konstytucji 3-go Maja 3 50-048 Wroclaw
Aleja Generała Tadeusza Bora-Komorowskiego 25, Quattro Business Park Five, 31-476 Kraków, Poland

Contact phone:

+48 122110650
Success
Thank you.
Your request has been received.