Testing / JUnit6 Interview Questions
What are nested tests in JUnit 6 and what is the @TestClassOrder/@TestMethodOrder inheritance change?
Nested tests (inner classes annotated with @Nested) allow you to organise tests hierarchically, grouping related tests and sharing setup/teardown context. JUnit 6 introduces a notable change: @TestClassOrder and @TestMethodOrder are now recursively inherited by all @Nested classes, giving deterministic ordering throughout the hierarchy.
import org.junit.jupiter.api.*; @DisplayName("Shopping cart") @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class ShoppingCartTest { Cart cart; @BeforeEach void init() { cart = new Cart(); } @Test @Order(1) @DisplayName("is empty on creation") void isEmpty() { assertTrue(cart.isEmpty()); } // @TestMethodOrder(MethodOrderer.OrderAnnotation.class) inherited // by @Nested classes in JUnit 6 -- no need to repeat the annotation @Nested @DisplayName("when items are added") class WhenItemsAdded { @BeforeEach void addItems() { cart.add(new Item("apple", 1.00)); } @Test @Order(1) @DisplayName("is not empty") void isNotEmpty() { assertFalse(cart.isEmpty()); } @Test @Order(2) @DisplayName("total reflects added items") void totalIsCorrect() { assertEquals(1.00, cart.total()); } @Nested @DisplayName("when item is removed") class WhenItemRemoved { @BeforeEach void remove() { cart.remove("apple"); } @Test @Order(1) @DisplayName("is empty again") void isEmptyAgain() { assertTrue(cart.isEmpty()); } } } }
More Related questions...