Bird
Raised Fist0
JUnittesting~10 mins

@BeforeEach method in JUnit - Test Execution Trace

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of the @BeforeEach annotation in JUnit?
easy
A. To clean up resources after all tests have run
B. To run a method only once before all tests in the class
C. To mark a method as a test case
D. To run a method before each test method to set up test conditions

Solution

  1. Step 1: Understand the role of @BeforeEach

    The @BeforeEach annotation marks a method to run before every test method, preparing the test environment.
  2. Step 2: Compare with other annotations

    @BeforeAll runs once before all tests, @Test marks test methods, and cleanup is done with @AfterAll or @AfterEach.
  3. Final Answer:

    To run a method before each test method to set up test conditions -> Option D
  4. Quick Check:

    @BeforeEach = setup before every test [OK]
Hint: Runs setup before each test method to avoid repetition [OK]
Common Mistakes:
  • Confusing @BeforeEach with @BeforeAll
  • Thinking it runs after tests
  • Using it to mark test methods
2. Which of the following is the correct way to declare a @BeforeEach method in JUnit 5?
easy
A. public void setup() { }
B. @BeforeEach public void setup() { }
C. void @BeforeEach setup() { }
D. public @BeforeEach void setup() { }

Solution

  1. Step 1: Recall correct annotation syntax

    Annotations like @BeforeEach must be placed before the method signature with proper access modifier and return type.
  2. Step 2: Check each option

    @BeforeEach public void setup() { } correctly places @BeforeEach before a public void method. public void setup() { } lacks the annotation. public @BeforeEach void setup() { } incorrectly places the access modifier before the annotation (syntax error). void @BeforeEach setup() { } misplaces the annotation after the return type.
  3. Final Answer:

    @BeforeEach public void setup() { } -> Option B
  4. Quick Check:

    Annotation before method signature = correct [OK]
Hint: Annotation goes immediately before method declaration [OK]
Common Mistakes:
  • Placing annotation after method name
  • Omitting public access modifier
  • Missing parentheses in method declaration
3. Given the following JUnit 5 test class, what will be the output when running the tests?
import org.junit.jupiter.api.*;

class SampleTest {
  int count = 0;

  @BeforeEach
  void setup() {
    count++;
    System.out.println("Setup count: " + count);
  }

  @Test
  void testOne() {
    System.out.println("Test One count: " + count);
  }

  @Test
  void testTwo() {
    System.out.println("Test Two count: " + count);
  }
}
medium
A. Setup count: 1 Test One count: 1 Setup count: 1 Test Two count: 1
B. Setup count: 1 Test One count: 1 Test Two count: 1 Setup count: 2
C. Setup count: 1 Test One count: 1 Setup count: 2 Test Two count: 2
D. Setup count: 0 Test One count: 0 Setup count: 0 Test Two count: 0

Solution

  1. Step 1: Understand @BeforeEach execution

    The setup() method runs before each test, incrementing count and printing it.
  2. Step 2: Trace the output for each test

    Before testOne(), count becomes 1 and prints "Setup count: 1" then "Test One count: 1". Before testTwo(), count increments to 2 and prints "Setup count: 2" then "Test Two count: 2".
  3. Final Answer:

    Setup count: 1 Test One count: 1 Setup count: 2 Test Two count: 2 -> Option C
  4. Quick Check:

    @BeforeEach runs before each test, incrementing count [OK]
Hint: Remember @BeforeEach runs before every test method [OK]
Common Mistakes:
  • Assuming count resets before each test
  • Thinking @BeforeEach runs only once
  • Mixing order of print statements
4. Identify the error in the following JUnit 5 test class using @BeforeEach:
import org.junit.jupiter.api.*;

class TestExample {
  int value;

  @BeforeEach
  void initialize() {
    value = 10;
  }

  @Test
  void testValue() {
    Assertions.assertEquals(10, value);
  }

  @BeforeEach
  void reset() {
    value = 20;
  }
}
medium
A. Multiple @BeforeEach methods cause both to run before each test
B. Only the first @BeforeEach method runs, so value is 10 in test
C. JUnit throws an error because multiple @BeforeEach methods are not allowed
D. The test fails because value is never initialized

Solution

  1. Step 1: Understand multiple @BeforeEach methods behavior

    JUnit allows multiple methods annotated with @BeforeEach. All run before each test, but order is not guaranteed.
  2. Step 2: Analyze effect on variable value

    Both initialize() and reset() run before testValue(). Since reset() sets value last to 20, the assertion expecting 10 will fail.
  3. Final Answer:

    Multiple @BeforeEach methods cause both to run before each test -> Option A
  4. Quick Check:

    Multiple @BeforeEach methods all run before tests [OK]
Hint: Multiple @BeforeEach methods all run; last one may override setup [OK]
Common Mistakes:
  • Assuming only one @BeforeEach method runs
  • Expecting JUnit to throw error for multiple @BeforeEach
  • Ignoring method execution order
5. You want to test a calculator class where each test needs a fresh calculator instance. Which is the best way to use @BeforeEach to achieve this?
hard
A. Use @BeforeEach to create a new calculator instance before every test
B. Initialize the calculator instance once in a static block
C. Create a new calculator instance inside each test method
D. Reuse the same calculator instance for all tests without resetting

Solution

  1. Step 1: Understand test isolation needs

    Each test should have a clean calculator instance to avoid state carryover.
  2. Step 2: Choose setup method for fresh instance

    Using @BeforeEach to create a new instance before every test ensures isolation and avoids repeating code inside each test.
  3. Final Answer:

    Use @BeforeEach to create a new calculator instance before every test -> Option A
  4. Quick Check:

    @BeforeEach creates fresh state for each test [OK]
Hint: Use @BeforeEach to reset objects before every test [OK]
Common Mistakes:
  • Creating instances inside test methods causing repetition
  • Using static initialization causing shared state
  • Reusing instances without resetting state
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard