Stub
A lightweight mocking framework for Kotlin Multiplatform.
Stub generates mock implementations at compile time using a Kotlin compiler plugin — no reflection, no manual mock classes.
Works on JVM, Android, iOS, and JS.
Core DSL
| API | Description |
|---|
stub<T>() | Create a stub for any interface or final class |
every { } returns | Configure a return value |
every { } throws | Configure an exception |
every { } answers { } | Compute a return value dynamically |
verify { } | Assert a method was called |
any() | Match any argument |
eq(value) | Match by equality |
coEvery { } | every for suspend functions |
Usage
Basic example
import org.yarokovisty.stub.dsl.*
import kotlin.test.Test
import kotlin.test.assertEquals
{
: String
}
{
repository: UserRepository = stub()
{
every { repository.findById() } returns
assertEquals(, repository.findById())
verify { repository.findById() }
}
}
Argument matchers
every { repository.findById(any()) } returns "Unknown"
every { repository.findById(eq(1)) } returns "Alice"
repository.findById(1)
repository.findById(999)
Final class mocking
No open keyword needed — the compiler plugin handles it:
class DataSource {
fun load(): String = "real"
}
val dataSource: DataSource = stub()
every { dataSource.load() } returns "mocked"
Suspend functions
import kotlinx.coroutines.test.runTest
interface ApiService {
suspend fun fetchData(): String
}
@Test
fun testSuspend() = runTest {
val api: ApiService = stub()
coEvery { api.fetchData() } returns "async result"
assertEquals("async result", api.fetchData())
coVerify { api.fetchData() }
}
Clearing state
clearStubs(repository)
clearInvocations(repository)
Installation
Apply the compiler plugin and add the DSL dependency:
build.gradle.kts
plugins {
id("io.github.yarokovisty.stub.compiler") version "<version>"
}
kotlin {
sourceSets {
commonTest.dependencies {
implementation("io.github.yarokovisty:stub-dsl:<version>")
implementation("io.github.yarokovisty:stub-runtime:<version>")
implementation(libs.kotlin.test)
implementation(libs.kotlinx.coroutines.test)
}
}
}
Supported platforms
JVM, Android, iOS (iosArm64, iosSimulatorArm64, iosX64), JS (Node.js)
Requirements
| Dependency | Version |
|---|
| Kotlin | 2.2.20+ |
| Gradle | 8.14+ |
License
Copyright (c) YarokovistY. All rights reserved.