Testing / JUnit6 Interview Questions
What are the core annotations in JUnit 6 and what does each do?
The JUnit 6 annotation model is unchanged from JUnit 5 Jupiter -- this is by design, making migration from JUnit 5 to JUnit 6 primarily a version bump rather than an annotation rewrite.
| Annotation | Purpose | Notes |
|---|---|---|
| @Test | Marks a method as a test case | No parameters; replaces JUnit 4's @Test |
| @BeforeEach | Runs before each test method | Replaces JUnit 4's @Before |
| @AfterEach | Runs after each test method | Replaces JUnit 4's @After |
| @BeforeAll | Runs once before all tests in the class | Must be static unless @TestInstance(PER_CLASS) |
| @AfterAll | Runs once after all tests in the class | Must be static unless @TestInstance(PER_CLASS) |
| @Disabled | Skips the annotated test or class | Replaces JUnit 4's @Ignore |
| @DisplayName | Custom display name for the test | Supports Unicode, emojis, spaces |
| @Nested | Marks an inner class as a nested test class | Enables hierarchical test organisation |
| @Tag | Categorises tests for filtering | Replaces JUnit 4's @Category |
import org.junit.jupiter.api.*; import static org.junit.jupiter.api.Assertions.*; @DisplayName("Order service tests") class OrderServiceTest { OrderService service; @BeforeAll static void initAll() { System.out.println("Runs once before all tests"); } @BeforeEach void setUp() { service = new OrderService(); } @Test @DisplayName("New order has PENDING status") void newOrderIsPending() { Order order = service.create("item-1", 2); assertEquals(Status.PENDING, order.getStatus()); } @Test @Disabled("Not implemented yet") void cancelledOrderIsRefunded() { // TODO } @AfterEach void tearDown() { service = null; } @AfterAll static void tearDownAll() { System.out.println("Runs once after all tests"); } }
More Related questions...