@Nested Tests

Learn how to use the @Nested annotation to configure the test hierarchy.

Test methods are grouped in test classes. Test methods in a test class are typically related to the same test target. JUnit 5 supports nested tests that can easily express complicated test relationships. Nested tests are declared using the org.junit.jupiter.api.Nested annotation on non-static inner classes of the current test class.

User class

Let’s look at a concrete example to learn how to write nested tests. The class we’ll test is a service class that’s responsible for managing users. The code below shows the class User. This class has two properties, name and email.

Get hands-on with 1200+ tech skills courses.