Test Overview
This test demonstrates how JUnit lifecycle hooks @BeforeEach and @AfterEach manage setup and teardown for each test method. It verifies that setup runs before and teardown runs after the test.
This test demonstrates how JUnit lifecycle hooks @BeforeEach and @AfterEach manage setup and teardown for each test method. It verifies that setup runs before and teardown runs after the test.
import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; public class LifecycleHooksTest { private StringBuilder resource; @BeforeEach void setUp() { resource = new StringBuilder("start"); } @AfterEach void tearDown() { resource = null; } @Test void testModifyResource() { resource.append("-modified"); assertEquals("start-modified", resource.toString()); } @Test void testResourceIsFresh() { assertEquals("start", resource.toString()); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test runner starts and prepares to run testModifyResource | No resource initialized yet | - | PASS |
| 2 | @BeforeEach setUp() runs, initializing resource with 'start' | resource = 'start' | - | PASS |
| 3 | testModifyResource() runs, appending '-modified' to resource | resource = 'start-modified' | assertEquals("start-modified", resource.toString()) | PASS |
| 4 | @AfterEach tearDown() runs, setting resource to null | resource = null | - | PASS |
| 5 | Test runner prepares to run testResourceIsFresh | resource is null from previous teardown | - | PASS |
| 6 | @BeforeEach setUp() runs again, initializing resource with 'start' | resource = 'start' | - | PASS |
| 7 | testResourceIsFresh() runs, checking resource value | resource = 'start' | assertEquals("start", resource.toString()) | PASS |
| 8 | @AfterEach tearDown() runs, setting resource to null | resource = null | - | PASS |