0
0
JUnittesting~10 mins

Why lifecycle hooks manage setup and teardown in JUnit - Test Execution Impact

Choose your learning style9 modes available
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.

Test Code - JUnit 5
JUnit
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());
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test runner starts and prepares to run testModifyResourceNo resource initialized yet-PASS
2@BeforeEach setUp() runs, initializing resource with 'start'resource = 'start'-PASS
3testModifyResource() runs, appending '-modified' to resourceresource = 'start-modified'assertEquals("start-modified", resource.toString())PASS
4@AfterEach tearDown() runs, setting resource to nullresource = null-PASS
5Test runner prepares to run testResourceIsFreshresource is null from previous teardown-PASS
6@BeforeEach setUp() runs again, initializing resource with 'start'resource = 'start'-PASS
7testResourceIsFresh() runs, checking resource valueresource = 'start'assertEquals("start", resource.toString())PASS
8@AfterEach tearDown() runs, setting resource to nullresource = null-PASS
Failure Scenario
Failing Condition: If @BeforeEach setUp() does not initialize resource, tests fail due to NullPointerException or wrong value
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @BeforeEach method do in this test?
ARuns only once before all tests
BCleans up the resource after all tests finish
CInitializes the resource before each test method runs
DRuns after each test method to reset the resource
Key Result
Using lifecycle hooks like @BeforeEach and @AfterEach ensures each test starts fresh and cleans up after itself, preventing tests from affecting each other.