0
0
JUnittesting~5 mins

Execution order of lifecycle methods in JUnit

Choose your learning style9 modes available
Introduction

We use lifecycle methods to set up and clean up before and after tests run. Knowing their order helps us organize tests well.

When you need to prepare resources before any tests start.
When you want to reset data before each test runs.
When you want to clean up resources after each test.
When you want to release resources after all tests finish.
Syntax
JUnit
@BeforeAll
@BeforeEach
@Test
@AfterEach
@AfterAll

@BeforeAll and @AfterAll run once per test class.

@BeforeEach and @AfterEach run before and after every test method.

Examples
This shows the basic lifecycle methods in JUnit 5.
JUnit
@BeforeAll
static void setupAll() {
    // runs once before all tests
}

@BeforeEach
void setup() {
    // runs before each test
}

@Test
void testOne() {
    // test code
}

@AfterEach
void tearDown() {
    // runs after each test
}

@AfterAll
static void tearDownAll() {
    // runs once after all tests
}
This example prints messages showing the order of lifecycle method execution.
JUnit
@BeforeAll
static void init() {
    System.out.println("Before all tests");
}

@BeforeEach
void beforeEachTest() {
    System.out.println("Before each test");
}

@Test
void testA() {
    System.out.println("Test A running");
}

@AfterEach
void afterEachTest() {
    System.out.println("After each test");
}

@AfterAll
static void cleanup() {
    System.out.println("After all tests");
}
Sample Program

This test class has two tests. It prints messages to show the order lifecycle methods run.

JUnit
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class LifecycleOrderTest {

    @BeforeAll
    static void beforeAll() {
        System.out.println("BeforeAll");
    }

    @BeforeEach
    void beforeEach() {
        System.out.println("BeforeEach");
    }

    @Test
    void testOne() {
        System.out.println("TestOne");
    }

    @Test
    void testTwo() {
        System.out.println("TestTwo");
    }

    @AfterEach
    void afterEach() {
        System.out.println("AfterEach");
    }

    @AfterAll
    static void afterAll() {
        System.out.println("AfterAll");
    }
}
OutputSuccess
Important Notes

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

Each test method runs between @BeforeEach and @AfterEach.

Order helps avoid resource conflicts and keeps tests clean.

Summary

@BeforeAll runs once before all tests.

@BeforeEach runs before each test method.

@AfterEach runs after each test method.

@AfterAll runs once after all tests.