Testing / JUnit6 Interview Questions
What is the native Kotlin coroutine support in JUnit 6?
JUnit 6 adds first-class support for Kotlin suspend functions as test and lifecycle methods. In JUnit 5, testing coroutines required wrapping every test in runBlocking { }. JUnit 6 eliminates this boilerplate: the Jupiter engine manages the coroutine context internally.
// JUnit 5 (before): runBlocking required class NetworkServiceTest { @Test fun `should fetch user`(): Unit = runBlocking { val user = service.fetchUser("user-1") assertEquals("Alice", user.name) } @BeforeEach fun setUp(): Unit = runBlocking { service = NetworkService() service.connect() // suspend function } } // JUnit 6 (now): suspend directly supported class NetworkServiceTest { @Test suspend fun `should fetch user`() { // No runBlocking needed! val user = service.fetchUser("user-1") assertEquals("Alice", user.name) } @BeforeEach suspend fun setUp() { // Lifecycle methods can also be suspend service = NetworkService() service.connect() // suspend function -- no wrapping needed } @AfterEach suspend fun tearDown() { service.disconnect() } } // IMPORTANT NOTE: JUnit 6's suspend support is equivalent to // runBlocking -- it does NOT replace kotlin-coroutines-test // for testing concurrent behaviour, StateFlow, etc. // For full coroutine test control, use kotlinx-coroutines-test's // runTest in addition to JUnit 6.
More Related questions...