// build.gradle.kts:
// testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.+")
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.test.*
class UserService {
suspend fun fetchUser(id: Int): String {
delay(2000) // simulate network
return "User $id"
}
}
class UserServiceTest {
@Test
fun fetches_user_eventually() = runTest { // virtual time scheduler
val service = UserService()
val result = service.fetchUser(42)
assertEquals("User 42", result)
// Test finishes in ~0ms despite delay(2000) inside
}
@Test
fun two_parallel_calls() = runTest {
val service = UserService()
val (a, b) = listOf(
async { service.fetchUser(1) },
async { service.fetchUser(2) },
).awaitAll().let { it[0] to it[1] }
assertEquals("User 1", a)
assertEquals("User 2", b)
}
}
Create a free account and build your private vault. Share publicly whenever you want.