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.
22 січ 2020
2014
Інші статті
How to debug and solve the issue of Datanodes which were reported as Bad nodes?
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?
Listing 8 The JUnit4CustomRuleTester class
In listing 8, we use the previously defined CustomRule by doing the following:
- We declare a public CustomRule field and we annotate it with @Rule (1).
- 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.

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
In listing 9 we do the following:
- We declare CustomExtension as implementing the AfterEachCallback and BeforeEachCallback interfaces (1’).
- We override the afterEach method, to be executed after each test method from the testing class which is extended with CustomExtension (2’).
- 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