JUnit 5 allows you to create nested tests using the @Nested annotation. In this article, you will learn what the @Nested annotation is and how to use it.
What Is a Nested Test?
JUnit’s @Nested annotation signals that the class it associates with is an inner class, which is a member of another class. A nested test is a test class that contains the @Nested annotation, as this means that there is one (or more) inner class within a top-level test class. A nested class can appear within a top-level class, or within a class that is also nested.
Creating Java Classes to Test
A nested test class inherits all the features of its parent class. Therefore, the best time to create a nested test is when there is a logical grouping of test cases or when a single test case has different features. A good example of this is when you want to test a class’s ability to create useful objects. Another example is when a single method has two or more purposes.
Here’s an example class that you might use in a retail application, that demonstrates how you can create a nested test.
This Customer class contains all the components of a Java Class, complete with two methods.
Creating a Nested Test With JUnit 5
The Customer class has several constructors, getters, and setters, and two methods. You can create a nested class (within the Customer test class) that creates a new Customer object and tests all its components.
The CustomerTest class is the top-level test class to a nested CustomerBuilderTest class. CustomerBuilderTest creates a new Customer object and tests its components using assertion tests.
Executing the CustomerTest test class produces the following successful test results:
The names of the test classes and the test method are descriptive and comprehensive, thanks to the @DisplayName Annotation.
Knowing How to Test Software is Crucial
Technology is an important aspect of everyday life for most people. The stakes for creating software that does exactly what it is supposed to do have never been higher.
A self-driving car that miscalculates its proximity to another object can cause a major accident. Therefore, you need to test your application at every stage of its development.