0
0
JUnittesting~10 mins

@Nested inner classes in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates how to use @Nested inner classes in JUnit to group related test cases. It verifies that the outer and inner test methods run correctly and independently.

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

public class CalculatorTest {

    @Test
    void testAddition() {
        assertEquals(5, 2 + 3);
    }

    @Nested
    class SubtractionTests {

        @Test
        void testSimpleSubtraction() {
            assertEquals(2, 5 - 3);
        }

        @Test
        void testNegativeResult() {
            assertEquals(-1, 2 - 3);
        }
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test runner starts and loads CalculatorTest classJUnit test environment initialized-PASS
2Runs outer test method testAddition()CalculatorTest instance createdassertEquals(5, 2 + 3) verifies 5 equals 5PASS
3Discovers @Nested class SubtractionTestsJUnit prepares to run nested tests-PASS
4Runs nested test method testSimpleSubtraction()SubtractionTests instance createdassertEquals(2, 5 - 3) verifies 2 equals 2PASS
5Runs nested test method testNegativeResult()SubtractionTests instance createdassertEquals(-1, 2 - 3) verifies -1 equals -1PASS
6Test runner completes all testsAll tests executed successfully-PASS
Failure Scenario
Failing Condition: An assertion in any test method fails, e.g., testSimpleSubtraction expects wrong value
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @Nested annotation do in JUnit tests?
AGroups related test methods inside an inner class
BMarks a test method to be ignored
CRuns tests in parallel
DSpecifies a test method to run before all tests
Key Result
Using @Nested classes helps organize tests logically, making test suites easier to read and maintain by grouping related tests together.