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.
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.
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'"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit starts test run and prepares to run testListStartsEmpty | No list instance exists yet | - | PASS |
| 2 | JUnit calls @BeforeEach setUp() method to initialize list as empty ArrayList | list is a new empty ArrayList | - | PASS |
| 3 | JUnit runs testListStartsEmpty method | list is empty | assertTrue(list.isEmpty()) verifies list is empty | PASS |
| 4 | JUnit finishes testListStartsEmpty and prepares to run testAddItem | Previous list discarded | - | PASS |
| 5 | JUnit calls @BeforeEach setUp() method again to initialize a new empty list | list is a new empty ArrayList | - | PASS |
| 6 | JUnit runs testAddItem method | list is empty at start of testAddItem | - | PASS |
| 7 | testAddItem adds 'item1' to list | list contains one element: 'item1' | - | PASS |
| 8 | testAddItem asserts list size is 1 | list size is 1 | assertEquals(1, list.size()) verifies list size is 1 | PASS |
| 9 | testAddItem asserts first item is 'item1' | list.get(0) returns 'item1' | assertEquals('item1', list.get(0)) verifies first item | PASS |
| 10 | JUnit finishes testAddItem and completes test run | All tests passed | - | PASS |