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)
| Annotation | Description |
|---|---|
| @Test | Marks a method as a test method. |
| @BeforeEach | Runs before each test method. Used for setup. |
| @AfterEach | Runs after each test method. Used for cleanup. |
| @BeforeAll | Runs once before all test methods. Must be static. |
| @AfterAll | Runs once after all test methods. Must be static. |
| @Disabled | Disables a test method or class. |
| @DisplayName | Custom name for test class or method when displayed in test results. |
| @Nested | Declares nested test classes for better grouping. |
| @Tag | Adds 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:
@BeforeEachand@AfterEachare useful for per-test setup and teardown.@BeforeAlland@AfterAllare run once before and after all tests.@Disabledis used to skip tests.Assertionsis used to check expected vs actual outcomes.