// build.gradle.kts:
// testImplementation("io.mockk:mockk:1.13.+")
import io.mockk.*
import kotlinx.coroutines.test.runTest
import kotlin.test.*
interface UserRepo { suspend fun findById(id: Int): String? }
class UserService(private val repo: UserRepo) {
suspend fun greet(id: Int): String =
repo.findById(id)?.let { "Hello $it" } ?: "Unknown"
}
class UserServiceTest {
@Test
fun greets_known_user() = runTest {
val repo = mockk<UserRepo>()
coEvery { repo.findById(42) } returns "Alice"
val service = UserService(repo)
assertEquals("Hello Alice", service.greet(42))
coVerify(exactly = 1) { repo.findById(42) }
}
@Test
fun returns_unknown_when_repo_empty() = runTest {
val repo = mockk<UserRepo>()
coEvery { repo.findById(any()) } returns null
assertEquals("Unknown", UserService(repo).greet(99))
}
}
Create a free account and build your private vault. Share publicly whenever you want.