0
0
JUnittesting~5 mins

@BeforeEach method in JUnit

Choose your learning style9 modes available
Introduction

The @BeforeEach method runs before every test. It helps set up things so each test starts fresh and fair.

You want to create a new object before each test to avoid leftover data.
You need to reset a database or clear a list before running each test.
You want to open a connection or prepare resources before each test runs.
You want to avoid repeating the same setup code inside every test method.
Syntax
JUnit
@BeforeEach
void setup() {
    // setup code here
}

The method must be void and take no parameters.

It runs before each test method in the test class.

Examples
This creates a new Calculator object before each test.
JUnit
@BeforeEach
void init() {
    calculator = new Calculator();
}
This clears a list before each test to start empty.
JUnit
@BeforeEach
void resetList() {
    list.clear();
}
Sample Program

This test class uses @BeforeEach to create a new Counter before each test. This ensures tests do not affect each other.

JUnit
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

class CounterTest {
    private Counter counter;

    @BeforeEach
    void setup() {
        counter = new Counter();
    }

    @Test
    void testIncrement() {
        counter.increment();
        assertEquals(1, counter.getValue());
    }

    @Test
    void testReset() {
        counter.increment();
        counter.reset();
        assertEquals(0, counter.getValue());
    }
}

class Counter {
    private int value = 0;
    void increment() { value++; }
    void reset() { value = 0; }
    int getValue() { return value; }
}
OutputSuccess
Important Notes

Use @BeforeEach to keep tests independent and avoid bugs from shared state.

Do not put assertions inside @BeforeEach methods.

Summary

@BeforeEach runs before every test method.

It helps prepare a clean state for each test.

Use it to avoid repeating setup code in tests.