JUnit 5 Architecture. Part 6
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).
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.
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.
The JUnit 5 extension model may also be used to gradually replace the runners from JUnit 4. For the extensions which have already been created, the migration process is simple. For example:
- To migrate the Mockito tests, you need to replace, on the tested class, the annotation @RunWith(MockitoJUnitRunner.class) with the annotation @ExtendWith(MockitoExtension.class).
- To migrate the Spring tests, you need to replace, on the tested class, the annotation @RunWith(SpringJUnit4ClassRunner.class) with the annotation @ExtendWith(SpringExtension.class).
- At the time of writing this article, theres no extension for the Arquillian tests.
ConclusionsThe article discussed the the new architecture of JUnit 5 and how it emerged from the shortcomings of the previous JUnit 4 version. We emphasized the he modular approach of JUnit 5. It also showed the migration of the JUnit 4 code to JUnit 5, including here: migrating from rules to extensions; migrating custom rules to custom extensions.
Interested in JUnit? Check out our trainings.
Java and Web Technologies Expert