Which annotation is used to indicate a method is a test method in JUnit 5?

Java MCQ: Which annotation is used to indicate a method is a test method in JUnit 5?

a) @TestMethod
b) @Test
c) @RunTest
d) @JUnitTest

Answer:

b) @Test

Explanation:

The @Test annotation is used in JUnit 5 to indicate that a method is a test method. When a method is annotated with @Test, JUnit will execute that method as part of the testing process. The method can contain assertions to verify the expected behavior of the code being tested.

Here’s an example of a JUnit test method using the @Test annotation:

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class CalculatorTest {

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

In this example, the testAdd method is marked with @Test, indicating that it is a test case that JUnit should run. The assertEquals method is used to check that the result of the add method is correct.

The @Test annotation is the cornerstone of creating test cases in JUnit, enabling developers to write and organize tests effectively.

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