Migrating from JUnit 4 to JUnit 5: replacing rules with the extension model. Part 5
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.
12 лют 2020
1319
Інші статті
How to incrementally migrate the data from RDBMS to Hadoop using Sqoop Incremental Last Modified technique?
How to implement Slowly Changing Dimensions(SCD) Type 2 in Spark?
How to incrementally migrate the data from RDBMS to Hadoop using Sqoop Incremental Append technique?
Why MongoDB don't fetch all the matching documents for the query fired
How to solve the issue of full disk utilization in HDFS Namenode
Can We Use HDFS as Back-up Storage?
How to do Indexing in MongoDB with Elastic Search? Part 1
How to do Indexing in MongoDB with Elastic Search? Part 2
How to store data on browser using NoSQL IndexedDB?
How to Apply MBTI in HR: Motivation for every day. Groups of People & their Motivations
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.
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