Java MCQ: Which annotation is used to run a method after each test in JUnit 5?
a) @AfterTest
b) @After
c) @AfterEach
d) @Cleanup
Answer:
c) @AfterEach
Explanation:
The @AfterEach
annotation in JUnit 5 is used to run a method after each test method in the test class. This is useful for cleaning up resources, resetting state, or performing any other necessary teardown tasks after each test has run.
Here’s an example:
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
private Calculator calc;
@BeforeEach
public void setUp() {
calc = new Calculator();
}
@AfterEach
public void tearDown() {
calc = null; // Clean up after each test
}
@Test
public void testAdd() {
int result = calc.add(2, 3);
assertEquals(5, result);
}
}
In this example, the tearDown()
method is annotated with @AfterEach
, which means it will be run after each test method in the class. The tearDown()
method sets the Calculator
instance to null
, effectively cleaning up resources used during the test.
The @AfterEach
annotation ensures that any necessary cleanup is performed after each test, helping to maintain test isolation and prevent side effects between tests.