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

The last article in our series on JUnit 4 versus JUnit 5.

Listing 10 The JUnit5CustomExtensionTester class

JUnit5CustomExtensionTester class.PNG

In listing 10, we do the following:

  1. We extend JUnit5CustomExtensionTester with the CustomExtension class (1).
  2. We create the myCustomRuleTest method and annotate it with @Test (2).


As the test class is extended with the CustomExtension class, the previously defined beforeEach and afterEach methods are executed before and after each test method respectively.

The result of the execution of this test is shown in figure 2. The effective execution of the test is surrounded by the additional messages.

execution of JUnit5CustomExtensionTester.png
Figure 2 The result of the execution of JUnit5CustomExtensionTester.

We remark the clear difference in code clarity and code length between JUnit 4 and JUnit 5. The JUnit 4 approach needs to work with three classes, the JUnit 5 approach needs to work with only two classes. The code to be executed before and after each test method is isolated into a dedicated method with a clear name. On the side of the testing class, you only need to annotate it with @ExtendWith.

Conclusions


This article has demonstrated the migration from the JUnit 4 rules to the JUnit 5 extensions through examples that have been detailed with comments. We have migrated code using exceptions rules, temporary rules and custom rules and we have contrasted the original code to the new JUnit 5 extensions approach, which is clearer and shorter. JUnit 4 rules are and will still be in use, because there is a large amount of already written tests. You may consider slowly migrating your code to the new JUnit 5 extensions approach.

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.