Skip to content
javahacks.dev
JUnit

JUnit Nested Tests to Structure Test Suites by Behaviour

Use JUnit Nested classes to group tests by state or behaviour, share setup with scoped BeforeEach, and keep large test classes readable.

6 min read
Summarize in AI
Flat illustration of a JUnit test run with one failing test, with the JUnit5, Jenkins and GitHub Actions logos.

A test class with 40 methods and six different setups is hard to read. @Nested splits it by context without splitting the file. JUnit 5 and JUnit 6 behave the same here.

The shape

java
@DisplayName("ShoppingCart")
class ShoppingCartTest {

    ShoppingCart cart;

    @BeforeEach
    void createCart() { cart = new ShoppingCart(); }

    @Nested
    @DisplayName("when empty")
    class WhenEmpty {

        @Test void totalIsZero() { assertEquals(Money.ZERO, cart.total()); }

        @Test void checkoutIsRejected() {
            assertThrows(EmptyCartException.class, cart::checkout);
        }
    }

    @Nested
    @DisplayName("with two items")
    class WithTwoItems {

        @BeforeEach
        void addItems() {
            cart.add(new Item("A-1", Money.of(10)));
            cart.add(new Item("B-2", Money.of(5)));
        }

        @Test void totalIsTheSum() { assertEquals(Money.of(15), cart.total()); }

        @Test void removingOneUpdatesTheTotal() {
            cart.remove("A-1");
            assertEquals(Money.of(5), cart.total());
        }

        @Nested
        @DisplayName("after a coupon")
        class AfterCoupon {
            @BeforeEach void apply() { cart.apply(Coupon.percent(10)); }
            @Test void totalIsDiscounted() { assertEquals(Money.of("13.50"), cart.total()); }
        }
    }
}

The report reads: ShoppingCart, when empty, total is zero. With two items, after a coupon, total is discounted. It documents behaviour in sentences, and a new teammate can see what states the class supports.

Order of callbacks

For totalIsDiscounted, JUnit runs createCart, then addItems, then apply, then the test. After the test, @AfterEach methods run from the innermost outward. This mirrors the nesting, so each level can assume everything outside is already set up. The full order is in lifecycle annotations.

The mechanics that trip people

  • Inner, not static. A @Nested class must be a non-static inner class, because it uses the outer instance. A static class is not discovered as nested.
  • One instance per test. The outer class is instantiated for each test too. The default lifecycle gives each test a fresh object, so fields do not leak between tests.
  • **@BeforeAll and @AfterAll.** They are static in the default lifecycle, which inner classes cannot declare before Java 16. With Java 16 and later, inner classes may declare static members, so it works on a modern JDK. Using @TestInstance(PER_CLASS) avoids the question.

Naming

Name the outer class after the unit (ShoppingCartTest), nested classes after states (WhenEmpty, WithTwoItems), and methods after outcomes (checkoutIsRejected). Combined with @DisplayName, the tree in the IDE becomes a specification. See DisplayName and conventions.

When to use it

Nest when the same unit has several meaningful states, as above. Do not nest to group by method name, which adds a level and no information. Keep the depth at two or three, and use the outer class for setup shared by every context. Past that, split the class under test, in the spirit of the single responsibility principle.

A realistic example

A ShoppingCart class has several states: empty, with items, and checked out. Writing every test as a flat method with a long name, addItemToEmptyCartIncreasesCount, removeItemFromCartWithOneItemEmptiesIt, scales badly. With nested classes, class WhenEmpty, class WithItems and class AfterCheckout, each has its own @BeforeEach that builds the cart in that state, and the test names become short: count_is_zero, total_is_sum_of_prices, cannot_add_items. The report groups the tests by state, and a failure reads like a sentence: "ShoppingCart, with items, total is sum of prices".

Setup flows from outside to inside

The outer class's @BeforeEach runs before the nested class's, so the outer setup creates the common objects and each nested level refines the state. That is the real design benefit: a state is described once, by the code that sets it up, and the tests inside only assert. If you find yourself repeating setup lines in many tests of a flat class, the structure is asking for a nested class.

What not to nest

Do not nest more than two levels. A third level makes the setup chain long enough that no one can tell what state a test runs in without reading three methods. Do not nest to group unrelated tests by topic, which a plain separate class does better. And remember that @BeforeAll in a nested class was a surprise before Java 16, because inner classes could not declare static methods, so it needed the per-class lifecycle. On Java 16 and later a static method in a nested class is legal, and a project on Java 25 does not have that restriction.

Reports and the IDE

IDEs show the nesting as a tree, and build reports show the display names joined. Give each nested class a @DisplayName that reads as a condition, "when the cart is empty", and each test a name that reads as the outcome, "has a zero total", and the output reads as a specification. That is the reason many teams adopt the style, and it makes failures in CI readable to people who did not write the test.

Mixing with parameterized tests

A nested class can hold parameterized tests, which is useful when a state has many input cases. The @MethodSource factory is usually static, and on Java 16 and later a nested class can declare one. On older runtimes, use the per-class lifecycle on that class, or point at a static method in the outer class by its fully qualified name. Check this when a parameterized test in a nested class fails with a message about a non-static factory.

A complete example

java
class ShoppingCartTest {

    ShoppingCart cart;

    @BeforeEach
    void createCart() {
        cart = new ShoppingCart();
    }

    @Nested
    @DisplayName("when empty")
    class WhenEmpty {
        @Test
        void total_is_zero() {
            assertEquals(BigDecimal.ZERO, cart.total());
        }

        @Test
        void checkout_is_rejected() {
            assertThrows(IllegalStateException.class, cart::checkout);
        }
    }

    @Nested
    @DisplayName("with one item")
    class WithOneItem {
        @BeforeEach
        void addItem() {
            cart.add(new Item("keyboard", new BigDecimal("49.90")));
        }

        @Test
        void total_is_the_item_price() {
            assertEquals(new BigDecimal("49.90"), cart.total());
        }
    }
}

Read the structure as a specification: an empty cart has a zero total and rejects checkout, and a cart with one item totals that item's price. Each state is built once, the tests under it only assert, and a new state is a new class and not a new copy of the setup. The outer @BeforeEach runs for every nested test, so the cart always starts fresh.

Pitfalls with state and mocks

An inner class can read the outer instance's fields, so an outer mock or fixture is shared by the nested tests in one run. Extensions such as MockitoExtension apply to nested classes when declared on the outer class, and a @Mock field in the outer class is available inside. If a nested test seems to see leftovers from another, check that the field is created in a @BeforeEach and not in a field initializer of a class with per-class lifecycle.

Keeping the suite maintainable

Review nested structure the way you review code. A new test that does not fit any state may mean a state is missing, and a state with a single test may be better written as a flat test with a clear name. Prefer a few well-named states to many small ones, and delete a nested class when its setup becomes the same as its parent's.

Where this does not apply

Spring test annotations on a @Nested class are inherited from the enclosing class when @NestedTestConfiguration is the default, so a nested test shares the application context instead of starting another. The reference is Nested Tests, the [@Nested Javadoc](https://docs.junit.org/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Nested.html) has the rules, and writing tests is the starting point.

Also inTesting
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.