Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

What are @Nested tests in JUnit 5 and when do they improve readability?

@Nested marks a non-static inner class inside a test class, and the tests in it run with the outer class's setup: the outer @BeforeEach methods run first, then the inner ones. That lets us group tests by situation, such as when the account is empty and when the account is overdrawn, in a given-when-then style where each group adds its own setup. They improve readability when one subject has several distinct states, but one or two levels of nesting is usually enough; deeper trees become harder to follow than flat tests.

Why this question is asked

A test class for a real domain object often has 30 test methods with names like withdrawFromEmptyAccountWithOverdraftAllowedFails. The information is there, but it is crammed into method names, and the setup for each situation is repeated. Interviewers ask about @Nested to see whether we care about test structure as documentation. In this answer, we will recap what an inner class is, build a nested test step by step, see the order in which setup runs, look at the report it produces, and discuss when nesting helps and when it hurts.

1A Quick Recap of Inner Classes

In Java, a class declared inside another class without the static keyword is an inner class. Each instance of it is tied to an instance of the outer class, so it can read and change the outer instance's fields. A static nested class has no such link.

JUnit's @Nested relies on that link. It requires a non-static inner class, so that the inner tests can use the fields the outer setup prepared. When JUnit runs a test in a nested class, it first creates the outer instance, runs the outer @BeforeEach methods on it, then creates the inner instance and runs the inner @BeforeEach methods.

2Grouping Tests by Situation

Here is an account test grouped by the account's state. The outer class creates the account; each nested class puts it into one situation; the tests inside describe what happens in that situation.

Java
@DisplayName("An account")
class AccountTest {
Account account;
@BeforeEach void createAccount() { account = new Account("ACC-1"); } // runs first for every test
@Nested @DisplayName("when empty")
class WhenEmpty {
@Test @DisplayName("rejects a withdrawal")
void rejectsWithdrawal() {
assertThrows(InsufficientFundsException.class, () -> account.withdraw(new BigDecimal("10")));
}
}
@Nested @DisplayName("when overdrawn")
class WhenOverdrawn {
@BeforeEach void overdraw() { // runs after createAccount
account.enableOverdraft(new BigDecimal("100"));
account.withdraw(new BigDecimal("50"));
}
@Test @DisplayName("reports a negative balance")
void negativeBalance() { assertEquals(new BigDecimal("-50"), account.balance()); } // passes
@Test @DisplayName("charges a fee at month end")
void chargesFee() { /* ... */ }
}
}

Notice that the given part, the situation, lives in the nested class's @BeforeEach, and each test only contains the when and then parts. The setup for being overdrawn is written once, not in every test that needs it.

3The Order in Which Setup Runs

For negativeBalance, JUnit creates an AccountTest instance and runs createAccount, then creates a WhenOverdrawn instance tied to it and runs overdraw, then runs the test. Afterwards the inner @AfterEach methods run before the outer ones. Each test still gets fresh instances of both classes with the default lifecycle, so the groups stay isolated from each other.

Step throughRunning one nested test
  1. Create outer instanceAccountTest
  2. Outer @BeforeEachcreateAccount()
  3. Create inner instanceWhenOverdrawn, linked to the outer one
  4. Inner @BeforeEachoverdraw()
  5. TestnegativeBalance()
  6. Inner @AfterEach, then outer @AfterEach

6 steps in order. Play them, or step through them one at a time.

4What the Report Looks Like

IDEs and build reports show nested classes as a tree, and with @DisplayName the tree reads like a specification. A reader, including a product owner, can see the behaviour without opening the code.

Text
An account
when empty
rejects a withdrawal passed
when overdrawn
reports a negative balance passed
charges a fee at month end failed

So when a test fails, its position in the tree already tells us the situation. That is the main readability gain: the structure carries meaning that would otherwise be packed into long method names.

5When Nesting Helps and When It Hurts

@Nested helps when one subject has several distinct states that each have their own setup and several tests: an account that is empty, funded, overdrawn or closed; an order that is draft, paid or shipped. It also helps when tests share an expensive outer setup and only differ in a small extra step.

It hurts when nesting goes deep. With three or four levels, understanding one test means reading four @BeforeEach methods spread across the file, each changing shared fields. Then the test is harder to follow than a flat one with a clear helper method. As a rule, one or two levels is usually enough. Nesting also adds nothing for a class with five simple tests; there, plain methods with good display names are clearer.

6Follow-up questions

Can a @Nested class have @BeforeAll methods?

Historically not easily, because inner classes could not declare static methods before Java 16, so a nested class needed @TestInstance(Lifecycle.PER_CLASS) for @BeforeAll. On Java 16 and later, inner classes may have static members, and recent JUnit versions allow static @BeforeAll in @Nested classes; check your JUnit version.

Why must the class be non-static?

Because JUnit runs the outer setup on an outer instance and the inner tests need access to it. A static nested class has no outer instance, so JUnit does not treat a static class annotated with @Nested as a nested test class, and its tests would not share the outer setup.

Do @Nested tests work with Spring tests?

Yes. Nested classes inherit the outer class's Spring test configuration by default, so a @SpringBootTest outer class gives its nested classes the same application context, and @NestedTestConfiguration controls whether they inherit or override it.

7Conclusion

In this answer, we saw that @Nested marks a non-static inner class whose tests run after the outer class's @BeforeEach methods, so each nested class can add the setup for one situation in a given-when-then style. With display names, the report reads as a tree of behaviours. Nesting improves readability when a subject has distinct states with their own setup, but one or two levels is usually enough before it becomes harder to follow than flat tests.

What to say in the interviewAbout 90 seconds aloud

Open with

@Nested lets me put a non-static inner class inside a test class, and its tests run with the outer class's setup. For each nested test, JUnit creates the outer instance and runs the outer @BeforeEach, then creates the inner instance and runs the inner @BeforeEach, then the test, and the teardown goes in reverse.

Then, if they want more

Because the inner class is linked to the outer instance, it can use the fields the outer setup created. I use it to group tests by situation.

For an account, the outer setup creates the account, a nested class when empty has the tests for an empty account, and a nested class when overdrawn has a @BeforeEach that enables the overdraft and withdraws, and then tests like reports a negative balance.

That gives a given-when-then structure: the situation is written once in the nested setup and each test only has the action and the check. With display names, the report reads like a specification tree, so a failure already tells me the situation. It helps most when a subject has several states, each with its own setup and several tests.

I keep it to one or two levels, because deeper nesting means reading several setup methods to understand one test, and for a small class flat tests are clearer.

About this answer

Last updated
12 November 2026
Versions it names
Java 16
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
JUnit user guide
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What are @Nested tests in JUnit 5 and when do they improve readability?": https://scrivio-interview-library.netlify.app/java/junit/d40a4645fc/