0
0
JUnittesting~5 mins

Why lifecycle hooks manage setup and teardown in JUnit

Choose your learning style9 modes available
Introduction

Lifecycle hooks help prepare things before tests run and clean up after tests finish. This keeps tests neat and avoids repeated code.

When you need to open a database connection before each test and close it after.
When you want to create test data before tests and remove it after tests run.
When you need to reset shared settings or variables before each test.
When you want to start a server before tests and stop it after all tests complete.
Syntax
JUnit
@BeforeEach
void setup() {
    // code to run before each test
}

@AfterEach
void teardown() {
    // code to run after each test
}

@BeforeEach runs before every test method.

@AfterEach runs after every test method.

Examples
This example prints messages before and after each test.
JUnit
@BeforeEach
void setup() {
    System.out.println("Starting test");
}

@AfterEach
void teardown() {
    System.out.println("Test finished");
}
@BeforeAll and @AfterAll run once before and after all tests in the class.
JUnit
@BeforeAll
static void initAll() {
    System.out.println("Setup once before all tests");
}

@AfterAll
static void tearDownAll() {
    System.out.println("Cleanup once after all tests");
}
Sample Program

This test class uses @BeforeEach and @AfterEach to print messages around each test. It shows setup and teardown happening for every test method.

JUnit
import org.junit.jupiter.api.*;

public class SampleTest {

    @BeforeEach
    void setup() {
        System.out.println("Setup before test");
    }

    @AfterEach
    void teardown() {
        System.out.println("Teardown after test");
    }

    @Test
    void testOne() {
        System.out.println("Running testOne");
        Assertions.assertTrue(true);
    }

    @Test
    void testTwo() {
        System.out.println("Running testTwo");
        Assertions.assertEquals(2, 1 + 1);
    }
}
OutputSuccess
Important Notes

Use lifecycle hooks to avoid repeating setup and cleanup code in every test.

Make sure @BeforeEach and @AfterEach methods do not fail, or tests may be affected.

@BeforeAll and @AfterAll must be static methods in JUnit 5.

Summary

Lifecycle hooks run code before and after tests to manage setup and teardown.

This keeps tests clean and avoids repeating code.

@BeforeEach/@AfterEach run before/after each test; @BeforeAll/@AfterAll run once for all tests.