In JUnit testing, why should each test method be independent from others?
Think about what happens if tests rely on each other's data or state.
Test independence ensures that tests do not affect each other, so they can run in any order and still produce reliable results.
Consider these two JUnit test methods. What will be the output if testB runs before testA?
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class SampleTest { private static int counter = 0; @Test public void testA() { counter = 5; assertEquals(5, counter); } @Test public void testB() { assertEquals(5, counter); } }
Remember static variables keep their value across tests unless reset.
testB expects counter to be 5 but it is 0 initially. Since testB runs first, it fails. testA sets counter to 5 and passes.
Which assertion best ensures that a JUnit test is independent and does not rely on previous test state?
Think about where the test data comes from and if it is initialized fresh each time.
Using @BeforeEach to set up expected values ensures each test runs with fresh data, making it independent.
These JUnit tests sometimes fail and sometimes pass. What is the most likely cause?
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; public class FlakyTest { private static List<String> sharedList = new ArrayList<>(); @Test public void testAdd() { sharedList.add("item"); assertEquals(1, sharedList.size()); } @Test public void testClear() { sharedList.clear(); assertEquals(0, sharedList.size()); } }
Look at how the sharedList is used and modified.
Using a static shared list modified by tests causes flaky results depending on test execution order.
Which JUnit 5 feature helps guarantee test independence by resetting state before each test method?
Think about how to prepare the environment freshly for each test.
@BeforeEach runs before every test method, allowing fresh setup and ensuring tests do not share state.