Newly-Introduced JUnit 5 Annotations and Classes. Nested tests
3. Nested tests
An inner class means a class that is a member of another class. It can access any private instance variable of the outer class, as it’s effective part of that outer class. The typical use case is when two classes are tightly coupled, and it’s logical to provide direct access from the inner one to all instance variables of the outer one.
Following this tightly coupled idea, nested tests give the test writer more capabilities to express the relationship among several groups of tests. Inner classes may be package private.
Let’s presume we have a program that works with customers. Customers have a gender, a first name and a last name. Sometimes, they may have a middle name and a known date when they have become customers. As some parameters may be or may not be present, the engineers are using the builder pattern to create a customer and to test the correct creation.
Listing 4 demonstrates the usage of the @Nested annotation into the class NestedTestsTest. The customer under test is “John Michael Smith” (he has a middle name) and the date when he became a customer is also known.
The main test is NestedTestsTest (1) and it’s tightly coupled with the nested test BuilderTest (2).
First, NestedTestsTest defines the first name and the last name of a customer which is used for all nested tests (3).
The nested test, BuilderTest, verifies the construction of a Customer object (4) with the help of the builder pattern (5). The verification of the equality of fields is made at the end of the customerBuilder test (6).