JUnit 5 Nested Tests: Organizing Complex Test Hierarchies with @Nested
@Nested in JUnit 5 lets you group related tests into inner classes that share setup and describe behavior in structured layers. The result is tests that read like specifications: outer class = component, inner class = context or state, test methods = expected behaviors. This post shows when and how to use @Nested effectively, including shared fixture patterns and the lifecycle rules you need to know.
Test files grow fast. A service class with 10 methods, 3-5 test scenarios each, ends up with 30-50 test methods in a single flat class. Finding the test for "what happens when the cart is empty and the user is a guest?" means scrolling through noise.
@Nested classes solve this by letting you organize tests into a hierarchy that mirrors your specification. This post covers the mechanics, the lifecycle rules, and the patterns that make nested tests genuinely useful rather than just visual indentation.
What @Nested Does
@Nested marks a non-static inner class as a test class. JUnit 5 treats it as a full test class with its own setup methods, but it lives inside the outer class and has access to the outer instance.
class ShoppingCartTest {
private ShoppingCart cart;
@BeforeEach
void setUp() {
cart = new ShoppingCart();
}
@Nested
class WhenEmpty {
@Test
void totalShouldBeZero() {
assertThat(cart.total()).isEqualTo(Money.ZERO);
}
@Test
void itemCountShouldBeZero() {
assertThat(cart.itemCount()).isEqualTo(0);
}
@Test
void checkoutShouldThrowEmptyCartException() {
assertThrows(EmptyCartException.class, () -> cart.checkout());
}
}
@Nested
class WhenItemsAreAdded {
@BeforeEach
void addItems() {
cart.add(new Item("Widget", Money.of(9.99)));
cart.add(new Item("Gadget", Money.of(14.99)));
}
@Test
void totalShouldSumAllItems() {
assertThat(cart.total()).isEqualTo(Money.of(24.98));
}
@Test
void itemCountShouldReflectAddedItems() {
assertThat(cart.itemCount()).isEqualTo(2);
}
@Nested
class WithDiscountCode {
@BeforeEach
void applyDiscount() {
cart.applyDiscount("SAVE10");
}
@Test
void totalShouldBeReducedByDiscount() {
assertThat(cart.total()).isEqualTo(Money.of(22.48));
}
}
}
}The test display in your IDE or CI reports shows the hierarchy:
ShoppingCartTest
WhenEmpty
✓ totalShouldBeZero
✓ itemCountShouldBeZero
✓ checkoutShouldThrowEmptyCartException
WhenItemsAreAdded
✓ totalShouldSumAllItems
✓ itemCountShouldReflectAddedItems
WithDiscountCode
✓ totalShouldBeReducedByDiscountThis is readable without comments. The nesting tells the story.
Lifecycle Execution Order
Before using @Nested, you need to understand exactly how setup and teardown methods execute across nested levels. The rule is:
Outer@BeforeEachruns before inner@BeforeEach. Inner@AfterEachruns before outer@AfterEach.
For the shopping cart example, when WhenItemsAreAdded.WithDiscountCode.totalShouldBeReducedByDiscount runs:
- Outer
ShoppingCartTest.setUp()— creates freshcart WhenItemsAreAdded.addItems()— adds two itemsWithDiscountCode.applyDiscount()— applies discount- Test method runs
- Any
@AfterEachinWithDiscountCode(if present) - Any
@AfterEachinWhenItemsAreAdded(if present) - Any
@AfterEachinShoppingCartTest(if present)
Each test gets a fresh ShoppingCart from step 1. The inner @BeforeEach methods are additive — they build on top of the outer setup, not instead of it.
@BeforeAll in Nested Classes
@BeforeAll is trickier. By default, JUnit 5 creates a new test instance per test method, which means @BeforeAll methods must be static. But non-static inner classes can't have static members in Java.
You have two options:
Option 1: Change the test instance lifecycle to PER_CLASS
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class DatabaseIntegrationTest {
private DataSource dataSource;
@BeforeAll
void initDatabase() {
dataSource = createTestDataSource();
runMigrations(dataSource);
}
@Nested
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class UserRepository {
private UserRepo repo;
@BeforeAll
void setupRepo() {
repo = new UserRepo(dataSource);
}
@Test
void findById_shouldReturnUser() {
// uses both dataSource and repo
}
}
}PER_CLASS means one instance per test class, not per method. @BeforeAll can be non-static. The tradeoff: tests share state between methods, so you need to be careful about mutation.
Option 2: Use @RegisterExtension for shared resources
For expensive resources like database connections, consider extracting them into extensions instead of relying on @BeforeAll in nested classes. Extensions compose better.
Naming Conventions That Work
The flat naming convention (testMethodName_whenCondition_shouldExpectation) doesn't apply well to nested tests. With @Nested, the structure carries the context. Use plain descriptive names:
class UserServiceTest {
@Nested
class Registration {
@Nested
class WhenEmailIsAlreadyTaken {
@Test
void shouldThrowDuplicateEmailException() { ... }
@Test
void shouldNotCreateANewAccount() { ... }
}
@Nested
class WhenPasswordIsTooShort {
@Test
void shouldThrowValidationException() { ... }
@Test
void shouldIncludeMinimumLengthInErrorMessage() { ... }
}
}
@Nested
class Login {
@Nested
class WithValidCredentials {
@Test
void shouldReturnAuthToken() { ... }
@Test
void shouldUpdateLastLoginTimestamp() { ... }
}
@Nested
class WithInvalidPassword {
@Test
void shouldThrowAuthenticationException() { ... }
@Test
void shouldIncrementFailedAttemptCount() { ... }
}
}
}This reads like a specification document. The test names are short because the context is in the class hierarchy.
@DisplayName for Readable Reports
Combine @Nested with @DisplayName for CI reports that read like sentences:
@DisplayName("ShoppingCart")
class ShoppingCartTest {
@Nested
@DisplayName("when empty")
class WhenEmpty {
@Test
@DisplayName("should have zero total")
void totalShouldBeZero() { ... }
@Test
@DisplayName("should throw EmptyCartException on checkout")
void checkoutShouldThrow() { ... }
}
}CI output becomes:
ShoppingCart
when empty
✓ should have zero total
✓ should throw EmptyCartException on checkoutWhether to use @DisplayName depends on your team's preference. Class and method names work fine without it; @DisplayName just makes the report more prose-like.
When @Nested Is the Right Tool
Use @Nested when:
- A class has multiple methods, and tests for each method have distinct setup requirements
- You're testing state transitions: empty state, partial state, complete state, error state
- You want to test one feature at multiple levels: unit, with dependencies, with external systems
- The test file is growing past 30-40 methods and navigation is becoming difficult
Don't use @Nested when:
- You only have 2-3 tests per scenario — the nesting adds overhead for little benefit
- The nested classes would have no
@BeforeEach— just group by naming convention instead - You're tempted to nest 4+ levels deep — that's a sign the component being tested is too complex
Accessing Outer Class Members
The inner class has access to the outer instance's fields and methods. This is the key difference from top-level test classes:
class PaymentProcessorTest {
private PaymentGateway gateway;
private PaymentProcessor processor;
@BeforeEach
void setUp() {
gateway = mock(PaymentGateway.class);
processor = new PaymentProcessor(gateway);
}
@Nested
class WhenGatewayIsUnavailable {
@BeforeEach
void makeGatewayFail() {
// accesses outer class 'gateway' field directly
when(gateway.charge(any())).thenThrow(new GatewayUnavailableException());
}
@Test
void shouldRetryThreeTimes() {
assertThrows(PaymentFailedException.class, () ->
processor.processPayment(Money.of(100)));
verify(gateway, times(3)).charge(any());
}
}
}The inner class modifies the mock created in the outer @BeforeEach. This pattern is clean because the mock setup lives in one place (outer setUp) and the scenario-specific behavior is in the nested class.
Integration with IDEs
IntelliJ IDEA and Eclipse both render @Nested hierarchies in the test explorer. The nested structure shows as a tree. When a test fails, the path includes the nested class names, so the error message tells you exactly which scenario failed:
ShoppingCartTest > WhenItemsAreAdded > WithDiscountCode > totalShouldBeReducedByDiscount FAILEDThis is far more diagnostic than ShoppingCartTest > testTotal_whenItemsWithDiscount_shouldReduce FAILED.
Summary
@Nested classes organize tests around behavior and context instead of method names. The outer class represents the component, nested classes represent states or scenarios, and test methods describe expected behaviors within that context. The lifecycle rule is that outer setup always runs first, building the context that inner setup refines. For @BeforeAll in nested classes, use @TestInstance(Lifecycle.PER_CLASS). Aim for no more than 2-3 levels of nesting, and let the class names tell the story so test method names can stay short.