import org.junit.jupiter.api.*; @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class SampleTest { @BeforeAll void beforeAll() { System.out.println("BeforeAll"); } @Test void testOne() { System.out.println("TestOne"); } @Test void testTwo() { System.out.println("TestTwo"); } @AfterAll void afterAll() { System.out.println("AfterAll"); } }
The @BeforeAll method runs once before any test methods. Then the test methods run in any order (usually the order they appear). Finally, the @AfterAll method runs once after all tests have completed.
Because the class uses @TestInstance(TestInstance.Lifecycle.PER_CLASS), the lifecycle allows non-static @BeforeAll and @AfterAll methods.
public class ResourceTest {
private static Resource resource;
@BeforeAll
static void setup() {
resource = new Resource();
}
@AfterAll
static void cleanup() {
resource = null;
}
@Test
void testResourceNotNull() {
Assertions.assertNotNull(resource);
}
// Which assertion below correctly verifies cleanup?
}The @AfterAll method sets resource to null. To verify cleanup, you assert that resource is null.
Option C uses assertNull, which is correct. Other options check for non-null or true/false conditions that do not match the expected null state.
import org.junit.jupiter.api.*; public class FailureTest { @AfterAll static void cleanup() { System.out.println("Cleaning up"); } @Test void testSomething() { Assertions.assertTrue(true); } }
By default, JUnit 5 requires @AfterAll methods to be static unless the test class is annotated with @TestInstance(TestInstance.Lifecycle.PER_CLASS).
In this code, the @AfterAll method is non-static and the class lacks the @TestInstance annotation, causing a runtime failure.
The @AfterAll method runs once after all tests in the class have finished. It is used to clean up shared resources or perform final actions.
Other options describe @BeforeEach, @AfterEach, or conditional test failure hooks, which are different.
Even when tests run in parallel threads, the @AfterAll method runs once after all tests in the class finish.
It is not repeated per thread and is not skipped in parallel mode.