0
0
JUnittesting~15 mins

@Nested inner classes in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify Calculator operations using @Nested inner classes in JUnit
Preconditions (2)
Step 1: Create a test class CalculatorTest
Step 2: Inside CalculatorTest, create a @Nested class AddTests
Step 3: In AddTests, write a test method testAddPositiveNumbers that asserts add(2,3) equals 5
Step 4: Inside CalculatorTest, create another @Nested class SubtractTests
Step 5: In SubtractTests, write a test method testSubtractPositiveNumbers that asserts subtract(5,3) equals 2
Step 6: Run the CalculatorTest class
✅ Expected Result: Both testAddPositiveNumbers and testSubtractPositiveNumbers pass successfully, showing that @Nested classes organize related tests
Automation Requirements - JUnit 5
Assertions Needed:
assertEquals for add method result
assertEquals for subtract method result
Best Practices:
Use @Nested annotation to group related test methods
Use descriptive method names for clarity
Keep test methods independent and focused
Use @BeforeEach if setup is needed inside nested classes
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int subtract(int a, int b) {
        return a - b;
    }
}

public class CalculatorTest {
    Calculator calculator = new Calculator();

    @Nested
    class AddTests {
        @Test
        void testAddPositiveNumbers() {
            assertEquals(5, calculator.add(2, 3));
        }
    }

    @Nested
    class SubtractTests {
        @Test
        void testSubtractPositiveNumbers() {
            assertEquals(2, calculator.subtract(5, 3));
        }
    }
}

This test class uses @Nested inner classes to group tests logically by operation type: addition and subtraction.

The Calculator class provides simple methods to add and subtract numbers.

Inside CalculatorTest, two nested classes AddTests and SubtractTests each contain one test method.

Each test method uses assertEquals to verify the expected result.

This structure helps organize tests clearly and makes it easier to maintain and understand related test cases.

Common Mistakes - 3 Pitfalls
{'mistake': 'Not using @Nested annotation on inner classes', 'why_bad': "JUnit will not recognize the inner classes as test containers, so tests inside won't run", 'correct_approach': 'Always annotate inner classes with @Nested to enable JUnit 5 to run their tests'}
Sharing mutable state between nested classes without setup
Writing multiple unrelated tests in one nested class
Bonus Challenge

Add a new @Nested class MultiplyTests with a test method that verifies multiplication of two numbers

Show Hint