JUnit Annotations

  

JUnit annotations are metadata tags used in Java unit testing with the JUnit framework. These annotations help control test execution, such as setup, teardown, test methods, and expected outcomes.


Common JUnit Annotations (JUnit 5)


AnnotationDescription
@TestMarks a method as a test method.
@BeforeEachRuns before each test method. Used for setup.
@AfterEachRuns after each test method. Used for cleanup.
@BeforeAllRuns once before all test methods. Must be static.
@AfterAllRuns once after all test methods. Must be static.
@DisabledDisables a test method or class.
@DisplayNameCustom name for test class or method when displayed in test results.
@NestedDeclares nested test classes for better grouping.
@TagAdds a tag for filtering or grouping tests (e.g., fast, slow, integration).




Example Code Using JUnit Annotations


import org.junit.jupiter.api.*;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class CalculatorTest {

    Calculator calculator;

    @BeforeAll
    void setupAll() {
        System.out.println("Initializing test class...");
    }

    @BeforeEach
    void setup() {
        calculator = new Calculator();
        System.out.println("Setting up before a test...");
    }

    @Test
    @DisplayName("Addition Test")
    void testAddition() {
        Assertions.assertEquals(5, calculator.add(2, 3));
    }

    @Test
    @DisplayName("Subtraction Test")
    void testSubtraction() {
        Assertions.assertEquals(1, calculator.subtract(4, 3));
    }

    @Test
    @Disabled("Feature not yet implemented")
    void testMultiplication() {
        Assertions.assertEquals(6, calculator.multiply(2, 3));
    }

    @AfterEach
    void tearDown() {
        System.out.println("Cleaning up after a test...");
    }

    @AfterAll
    void tearDownAll() {
        System.out.println("All tests completed.");
    }
}

// Simple Calculator class
class Calculator {
    int add(int a, int b) { return a + b; }
    int subtract(int a, int b) { return a - b; }
    int multiply(int a, int b) { return a * b; }
}



Important Points:

  • @BeforeEach and @AfterEach are useful for per-test setup and teardown.

  • @BeforeAll and @AfterAll are run once before and after all tests.

  • @Disabled is used to skip tests.

  • Assertions is used to check expected vs actual outcomes.