Which annotation is used to run a method once before all tests in JUnit 5?

Java MCQ: Which annotation is used to run a method once before all tests in JUnit 5?

a) @BeforeTest
b) @BeforeClass
c) @BeforeAll
d) @SetupAll

Answer:

c) @BeforeAll

Explanation:

The @BeforeAll annotation in JUnit 5 is used to run a method once before all tests in the test class. This is useful for performing time-consuming setup tasks that only need to be done once, such as initializing shared resources or setting up a database connection.

Here’s an example:

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

    @BeforeAll
    public static void init() {
        // Code to initialize shared resources
    }

    @Test
    public void testAdd() {
        Calculator calc = new Calculator();
        int result = calc.add(2, 3);
        assertEquals(5, result);
    }
}

In this example, the init() method is annotated with @BeforeAll, which means it will be executed once before any of the test methods in the class. Note that the method must be static because it is run before any instance of the test class is created.

The @BeforeAll annotation is ideal for tasks that need to be performed only once, reducing redundancy and improving test performance.

Reference links:

https://junit.org/junit5/
JUnit Tutorial

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top