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()); } } } }
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
