Java MCQ: Which annotation is used to run a method before each test in JUnit 5?
a) @BeforeTest
b) @Before
c) @BeforeEach
d) @Setup
Answer:
c) @BeforeEach
Explanation:
The @BeforeEach
annotation in JUnit 5 is used to run a method before each test method in the test class. This is useful for setting up common test data or state before running each test, ensuring that each test starts with a clean environment.
Here’s an example:
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CalculatorTest {
private Calculator calc;
@BeforeEach
public void setUp() {
calc = new Calculator();
}
@Test
public void testAdd() {
int result = calc.add(2, 3);
assertEquals(5, result);
}
}
In this example, the setUp()
method is annotated with @BeforeEach
, which means it will be run before each test method in the class. The Calculator
instance is initialized in setUp()
so that it is ready to be used in the testAdd()
method.
The @BeforeEach
annotation helps ensure that each test runs in isolation, with its own setup code executed before the test.