0
0
JUnittesting~15 mins

Why lifecycle hooks manage setup and teardown in JUnit - Automation Benefits in Action

Choose your learning style9 modes available
Verify setup and teardown using JUnit lifecycle hooks
Preconditions (2)
Step 1: Create a test class CalculatorTest
Step 2: Use @BeforeEach to initialize a Calculator object before each test
Step 3: Write a test method testAdd that adds two numbers and asserts the result
Step 4: Write a test method testSubtract that subtracts two numbers and asserts the result
Step 5: Use @AfterEach to set the Calculator object to null after each test
Step 6: Run the tests and observe that setup runs before each test and teardown runs after each test
✅ Expected Result: Each test method runs with a fresh Calculator instance initialized by @BeforeEach, and after each test the Calculator reference is cleared by @AfterEach. Tests pass successfully.
Automation Requirements - JUnit 5
Assertions Needed:
Assert that add method returns correct sum
Assert that subtract method returns correct difference
Best Practices:
Use @BeforeEach for setup to ensure fresh test state
Use @AfterEach for cleanup to avoid side effects
Keep tests independent and repeatable
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
    int subtract(int a, int b) {
        return a - b;
    }
}

public class CalculatorTest {
    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

    @AfterEach
    void tearDown() {
        calculator = null;
    }

    @Test
    void testAdd() {
        int result = calculator.add(5, 3);
        assertEquals(8, result, "5 + 3 should equal 8");
    }

    @Test
    void testSubtract() {
        int result = calculator.subtract(10, 4);
        assertEquals(6, result, "10 - 4 should equal 6");
    }
}

The @BeforeEach method setUp() runs before each test method. It creates a new Calculator instance so each test starts fresh, avoiding shared state.

The @AfterEach method tearDown() runs after each test method. It clears the Calculator reference to help with cleanup and avoid side effects.

Each test method uses the Calculator instance to perform operations and asserts the expected results. This shows how lifecycle hooks manage setup and teardown to keep tests independent and reliable.

Common Mistakes - 3 Pitfalls
Initializing the Calculator object inside each test method instead of using @BeforeEach
Not cleaning up resources or resetting state in @AfterEach
Using @BeforeAll or @AfterAll for instance setup and teardown
Bonus Challenge

Now add a test method that verifies multiplication using the same setup and teardown lifecycle hooks.

Show Hint