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
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.
Java and Web Technologies Expert