import org.junit.jupiter.api.*; public class SampleTest { private int counter = 0; @BeforeEach void setup() { counter += 5; System.out.println("Setup called. Counter = " + counter); } @Test void testCounter() { System.out.println("Test running. Counter = " + counter); Assertions.assertEquals(5, counter); } }
The @BeforeEach method runs before each test method. Since the test class instance is recreated for each test, the counter starts at 0 each time. The setup method adds 5, so the counter is 5 when the test runs.
import org.junit.jupiter.api.*; import java.util.*; public class ListTest { private List<String> items; @BeforeEach void setup() { items = new ArrayList<>(); items.add("A"); items.add("B"); items.add("C"); } @Test void testListSize() { // Which assertion is correct here? } }
The @BeforeEach method initializes the list with 3 elements. So the list size should be 3. Option A correctly asserts this.
import org.junit.jupiter.api.*; import java.util.*; public class NullTest { private List<String> items; @BeforeEach void setup() { List<String> items = new ArrayList<>(); items.add("X"); } @Test void testNotNull() { Assertions.assertEquals(1, items.size()); } }
The setup method declares a new local variable 'items' which shadows the instance variable. The instance variable remains null, causing NullPointerException in the test.
Static variables are shared across all instances of the class. Modifying them in @BeforeEach affects all tests because the variable is not reset automatically.
import org.junit.jupiter.api.*; public class LifecycleTest { @BeforeAll static void beforeAll() { System.out.println("BeforeAll"); } @BeforeEach void beforeEach() { System.out.println("BeforeEach"); } @Test void test() { System.out.println("Test"); } @AfterEach void afterEach() { System.out.println("AfterEach"); } @AfterAll static void afterAll() { System.out.println("AfterAll"); } }
JUnit 5 runs lifecycle methods in this order: @BeforeAll (once), @BeforeEach (before each test), @Test, @AfterEach (after each test), @AfterAll (once).