Testing / JUnit6 Interview Questions
What assertions does JUnit 6 provide and how do you use them?
JUnit 6 provides a rich set of assertions in org.junit.jupiter.api.Assertions. All methods are static and can be statically imported. Assertions fail the test immediately when the condition is not met (unlike assumptions, which abort silently).
import static org.junit.jupiter.api.Assertions.*; class AssertionsDemo { @Test void basicAssertions() { assertEquals(4, 2 + 2); assertNotEquals(5, 2 + 2); assertTrue(4 > 3); assertFalse(4 < 3); assertNull(null); assertNotNull("hello"); } @Test void assertionsWithMessages() { // Message is lazily evaluated (supplier) -- no cost if test passes assertEquals(4, 2 + 2, () -> "Expected 4 but was " + (2 + 2)); } @Test void groupedAssertions() { // assertAll: ALL assertions run even if some fail // Reports ALL failures, not just the first one assertAll("address", () -> assertEquals("London", address.city()), () -> assertEquals("UK", address.country()), () -> assertEquals("EC1A 1BB", address.postcode()) ); } @Test void exceptionAssertions() { // assertThrows: passes only if the lambda throws the expected type Exception ex = assertThrows(IllegalArgumentException.class, () -> new Order(null, -1)); assertEquals("Quantity must be positive", ex.getMessage()); } @Test void doesNotThrow() { assertDoesNotThrow(() -> new Order("item", 1)); } @Test void timeoutAssertions() { // Fails if the lambda takes longer than 1 second assertTimeout(Duration.ofSeconds(1), () -> Thread.sleep(500)); } }
Key difference -- assertAll vs chained assertions: chained assertions stop at the first failure. assertAll runs every assertion and reports all failures in one go, making it far more useful for validating complex objects with multiple fields.
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...
