Migrating from JUnit 4 to JUnit 5: replacing rules with the extension model. Part 5
Listing 10 The JUnit5CustomExtensionTester class
In listing 10, we do the following:
- We extend JUnit5CustomExtensionTester with the CustomExtension class (1’).
- 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.
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.
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.
Java and Web Technologies Expert