Testing / JUnit6 Interview Questions
How does JUnit 6 support for Kotlin differ from JUnit 5?
JUnit 6 significantly improves Kotlin support beyond just suspend function tests. The minimum Kotlin version is 2.2 and several common pain points from JUnit 5 Kotlin usage are addressed.
| Area | JUnit 5 pain point | JUnit 6 improvement |
|---|---|---|
| suspend tests | runBlocking required everywhere | Suspend functions work directly as @Test, @BeforeEach, @AfterEach |
| Nullability | API had no nullability contracts; !! needed | JSpecify annotations enable smart casts after assertNotNull |
| @BeforeAll in objects | Required @JvmStatic | @TestInstance(PER_CLASS) avoids @JvmStatic |
| kotlin-test interop | kotlin.test.assertEquals vs junit.jupiter assertions | JSpecify nullability aligns contracts between both |
| Minimum version | Kotlin 1.6+ | Kotlin 2.2+ required |
// Kotlin JUnit 6 test class import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.* @TestInstance(TestInstance.Lifecycle.PER_CLASS) class KotlinOrderTest { private lateinit var service: OrderService // No @JvmStatic needed with PER_CLASS lifecycle @BeforeAll suspend fun setUpAll() { service = OrderService() service.connect() // suspend function -- works directly! } @BeforeEach suspend fun setUp() { service.reset() // suspend function } @Test suspend fun `new order has pending status`() { val order = service.create("item-1", 2) // suspend call assertEquals(Status.PENDING, order.status) } @Test suspend fun `invalid quantity throws`() { assertThrows<IllegalArgumentException> { service.create("item-1", -1) // suspend call } } // JSpecify: smart cast works after assertNotNull @Test fun `smart cast after assertNotNull`() { val result: String? = service.findUser("user-1") assertNotNull(result) // JUnit 6 exposes @NonNull contract println(result.length) // No !! needed -- smart cast works } @AfterAll suspend fun tearDownAll() { service.disconnect() // suspend function } }
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...
