Java MCQ: Which annotation is used to run a method once after all tests in JUnit 5?
a) @AfterTest
b) @AfterClass
c) @AfterAll
d) @CleanupAll
Answer:
c) @AfterAll
Explanation:
The @AfterAll
annotation in JUnit 5 is used to run a method once after all tests in the test class. This is useful for performing cleanup tasks that should only be done once, such as closing a database connection or releasing shared resources.
Here’s an example:
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
@AfterAll
public static void tearDownAll() {
// Code to clean up shared resources
}
@Test
public void testAdd() {
Calculator calc = new Calculator();
int result = calc.add(2, 3);
assertEquals(5, result);
}
}
In this example, the tearDownAll()
method is annotated with @AfterAll
, meaning it will be executed once after all the test methods in the class have run. Like @BeforeAll
, this method must be static
because it is called after all tests have completed, before the test class is destroyed.
The @AfterAll
annotation is ideal for tasks that require a single cleanup operation after all tests have been executed, ensuring that shared resources are properly released.