Test Overview
This test demonstrates the use of the @AfterAll method in JUnit. It verifies that a cleanup method runs once after all tests complete.
This test demonstrates the use of the @AfterAll method in JUnit. It verifies that a cleanup method runs once after all tests complete.
import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; public class AfterAllExampleTest { private static int resource; @BeforeAll public static void setup() { resource = 5; System.out.println("Setup done"); } @Test public void testAddition() { int result = resource + 10; Assertions.assertEquals(15, result); } @Test public void testMultiplication() { int result = resource * 2; Assertions.assertEquals(10, result); } @AfterAll public static void cleanup() { resource = 0; System.out.println("Cleanup done"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | JUnit starts test run and calls @BeforeAll method | Static variable 'resource' is set to 5 | — | PASS |
| 2 | JUnit runs testAddition method | resource = 5 | Check if resource + 10 equals 15 | PASS |
| 3 | JUnit runs testMultiplication method | resource = 5 | Check if resource * 2 equals 10 | PASS |
| 4 | JUnit calls @AfterAll method after all tests | resource is reset to 0 | — | PASS |
@AfterAll annotation in JUnit 5?@AfterAll@AfterAll annotation is designed to mark a method that runs once after all test methods in the class have completed.@BeforeEach and @AfterEach run before and after each test method respectively, not once after all tests.@AfterAll runs once after all tests [OK]@AfterAll in JUnit 5?@AfterAll@AfterAll must be static and usually public to be accessible.@AfterAll method must be static and public [OK]import org.junit.jupiter.api.*;
public class TestExample {
static int count = 0;
@Test
void testOne() {
count++;
}
@Test
void testTwo() {
count++;
}
@AfterAll
public static void afterAll() {
System.out.println("Count: " + count);
}
}testOne() and testTwo() increment the static variable count by 1 each. So after both tests run, count will be 2.@AfterAll outputafterAll() method runs once after all tests and prints the current value of count, which is 2.import org.junit.jupiter.api.*;
public class SampleTest {
@AfterAll
void cleanup() {
System.out.println("Cleaning up");
}
@Test
void test() {
Assertions.assertTrue(true);
}
}@AfterAll method signature@AfterAll methods must be static unless the test class is annotated with @TestInstance(Lifecycle.PER_CLASS). Here, the method is non-static and no such annotation is present.@Test methods do not need to be static.@AfterAll method must be static -> Option A@AfterAll requires static method unless PER_CLASS used [OK]@AfterAll?@AfterAll rules@AfterAll method ensures proper cleanup.@AfterAll method that closes the connection -> Option DPass the test and this pattern moves unknown