0
0
JUnittesting~10 mins

@BeforeEach method in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses the @BeforeEach method to set up a fresh list before each test runs. It verifies that the list starts empty and can add an item correctly.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import java.util.List;

public class ListTest {
    private List<String> list;

    @BeforeEach
    void setUp() {
        list = new ArrayList<>();
    }

    @Test
    void testListStartsEmpty() {
        assertTrue(list.isEmpty(), "List should be empty before each test");
    }

    @Test
    void testAddItem() {
        list.add("item1");
        assertEquals(1, list.size(), "List size should be 1 after adding an item");
        assertEquals("item1", list.get(0), "First item should be 'item1'");
    }
}
Execution Trace - 10 Steps
StepActionSystem StateAssertionResult
1JUnit starts test run and prepares to run testListStartsEmptyNo list instance exists yet-PASS
2JUnit calls @BeforeEach setUp() method to initialize list as empty ArrayListlist is a new empty ArrayList-PASS
3JUnit runs testListStartsEmpty methodlist is emptyassertTrue(list.isEmpty()) verifies list is emptyPASS
4JUnit finishes testListStartsEmpty and prepares to run testAddItemPrevious list discarded-PASS
5JUnit calls @BeforeEach setUp() method again to initialize a new empty listlist is a new empty ArrayList-PASS
6JUnit runs testAddItem methodlist is empty at start of testAddItem-PASS
7testAddItem adds 'item1' to listlist contains one element: 'item1'-PASS
8testAddItem asserts list size is 1list size is 1assertEquals(1, list.size()) verifies list size is 1PASS
9testAddItem asserts first item is 'item1'list.get(0) returns 'item1'assertEquals('item1', list.get(0)) verifies first itemPASS
10JUnit finishes testAddItem and completes test runAll tests passed-PASS
Failure Scenario
Failing Condition: If @BeforeEach setUp() method does not initialize the list, list will be null causing NullPointerException
Execution Trace Quiz - 3 Questions
Test your understanding
What does the @BeforeEach method do in this test?
AIt runs only once before all tests
BIt runs after all tests to clean up resources
CIt runs before each test to set up a fresh list
DIt runs only if a test fails
Key Result
Using @BeforeEach ensures each test starts with a clean state, preventing tests from affecting each other and making tests reliable and independent.