0
0
JUnittesting~15 mins

@BeforeEach method in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify that the @BeforeEach method runs before each test method
Preconditions (2)
Step 1: Create a test class with a @BeforeEach annotated method that initializes a counter to zero
Step 2: Create two test methods that increment the counter and assert its value is 1
Step 3: Run the test class
✅ Expected Result: Each test method should see the counter reset to zero before incrementing, so both tests pass with counter value 1
Automation Requirements - JUnit 5
Assertions Needed:
Assert that the counter value is 1 inside each test method
Best Practices:
Use @BeforeEach to set up test data or state before each test
Keep test methods independent
Use clear and descriptive method names
Automated Solution
JUnit
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CounterTest {
    private int counter;

    @BeforeEach
    void resetCounter() {
        counter = 0;
    }

    @Test
    void testIncrementCounterFirst() {
        counter++;
        assertEquals(1, counter, "Counter should be 1 after increment");
    }

    @Test
    void testIncrementCounterSecond() {
        counter++;
        assertEquals(1, counter, "Counter should be 1 after increment");
    }
}

The @BeforeEach method resetCounter() runs before each test method. It sets the counter to zero every time. This ensures each test starts fresh.

Each test method increments the counter once and then checks if it equals 1. Because resetCounter() runs before each test, the counter is reset, so both tests pass independently.

This shows how @BeforeEach helps keep tests isolated and reliable.

Common Mistakes - 3 Pitfalls
Not using @BeforeEach and initializing variables inside test methods
Using @BeforeAll instead of @BeforeEach for mutable test data
Modifying shared static variables in @BeforeEach without resetting
Bonus Challenge

Now add a third test method that increments the counter twice and verify the counter value is 2

Show Hint