0
0
JUnittesting~5 mins

@Nested inner classes in JUnit

Choose your learning style9 modes available
Introduction

@Nested inner classes help organize tests by grouping related test cases together inside a main test class. This makes tests easier to read and maintain.

When you want to group tests that share a common setup or theme.
When testing different behaviors of the same class or method in separate groups.
When you want to clearly separate positive and negative test cases.
When you want to improve test readability by nesting related tests inside a parent test class.
Syntax
JUnit
@Nested
class InnerTestClass {
    @Test
    void testMethod() {
        // test code
    }
}

The @Nested annotation marks an inner class as a group of related tests.

Each @Nested class can have its own @BeforeEach and @AfterEach methods.

Examples
This nested class groups tests related to addition.
JUnit
@Nested
class AdditionTests {
    @Test
    void addsTwoNumbers() {
        assertEquals(4, 2 + 2);
    }
}
This nested class groups tests related to subtraction.
JUnit
@Nested
class SubtractionTests {
    @Test
    void subtractsTwoNumbers() {
        assertEquals(0, 2 - 2);
    }
}
Sample Program

This test class uses @Nested inner classes to group addition and subtraction tests separately. Each nested class has its own test methods.

JUnit
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {

    @Nested
    class AdditionTests {
        @Test
        void addsTwoPositiveNumbers() {
            assertEquals(5, 2 + 3);
        }

        @Test
        void addsNegativeAndPositiveNumber() {
            assertEquals(1, -2 + 3);
        }
    }

    @Nested
    class SubtractionTests {
        @Test
        void subtractsTwoNumbers() {
            assertEquals(1, 3 - 2);
        }
    }
}
OutputSuccess
Important Notes

Use descriptive names for nested classes to clearly show what group of tests they contain.

Nested classes can help reduce duplicate setup code by grouping related tests.

Summary

@Nested inner classes group related tests inside a main test class.

This improves test organization and readability.

Each nested class can have its own setup and teardown methods.