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.
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.
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); } } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and loads CalculatorTest class | JUnit test environment initialized | — | PASS |
| 2 | Runs outer test method testAddition() | CalculatorTest instance created | assertEquals(5, 2 + 3) verifies 5 equals 5 | PASS |
| 3 | Discovers @Nested class SubtractionTests | JUnit prepares to run nested tests | — | PASS |
| 4 | Runs nested test method testSimpleSubtraction() | SubtractionTests instance created | assertEquals(2, 5 - 3) verifies 2 equals 2 | PASS |
| 5 | Runs nested test method testNegativeResult() | SubtractionTests instance created | assertEquals(-1, 2 - 3) verifies -1 equals -1 | PASS |
| 6 | Test runner completes all tests | All tests executed successfully | — | PASS |
@Nested inner classes in JUnit tests?class CalculatorTest {
@BeforeEach void setup() { System.out.println("Setup main"); }
@Test void testAdd() { System.out.println("Test add"); }
@Nested
class MultiplyTests {
@BeforeEach void setup() { System.out.println("Setup nested"); }
@Test void testMultiply() { System.out.println("Test multiply"); }
}
}What will be the output when running the testMultiply method?class OuterTest {
@Nested
class InnerTest {
@Test void testSomething() {}
}
@Test void testOuter() {}
}Which of the following is a problem that will cause the tests NOT to run as expected?@Nested classes to separate addition and subtraction tests. Which of the following code snippets correctly applies @Nested classes with proper setup methods so that the main setup runs before each nested test setup?Pass the test and this pattern moves unknown