Comprehensive mocking library for Kotlin with native coroutine support and advanced DSL features.
—
Advanced mocking capabilities for static methods, object instances, and constructors, enabling comprehensive testing of complex Kotlin constructs and language features.
Mock static methods and properties of classes.
/**
* Mocks static methods of the specified classes
* @param classes Classes whose static methods should be mocked
*/
inline fun mockkStatic(vararg classes: KClass<*>)
/**
* Mocks static methods by class name
* @param classes Class names as strings
*/
inline fun mockkStatic(vararg classes: String)
/**
* Mocks static methods for the duration of a block
* @param classes Classes to mock
* @param block Block to execute with static mocking active
*/
inline fun mockkStatic(vararg classes: KClass<*>, block: () -> Unit)
/**
* Cancels static mocks
* @param classes Classes to unmock
*/
inline fun unmockkStatic(vararg classes: KClass<*>)
/**
* Cancels static mocks by class name
* @param classes Class names to unmock
*/
inline fun unmockkStatic(vararg classes: String)Usage Examples:
// Static class to mock
class FileUtils {
companion object {
fun readFile(path: String): String = "real content"
fun writeFile(path: String, content: String): Boolean = true
}
}
// Mock static methods
mockkStatic(FileUtils::class)
// Stub static method
every { FileUtils.readFile("test.txt") } returns "mocked content"
every { FileUtils.writeFile("test.txt", any()) } returns true
// Use static methods - they're now mocked
val content = FileUtils.readFile("test.txt") // "mocked content"
val success = FileUtils.writeFile("test.txt", "data") // true
// Verify static method calls
verify { FileUtils.readFile("test.txt") }
verify { FileUtils.writeFile("test.txt", "data") }
// Clean up
unmockkStatic(FileUtils::class)
// Scoped static mocking
mockkStatic(FileUtils::class) {
every { FileUtils.readFile(any()) } returns "scoped mock"
val result = FileUtils.readFile("any.txt") // "scoped mock"
}
// Static mock automatically cleaned up after blockMock Kotlin object instances (singletons).
/**
* Mocks Kotlin object instances
* @param objects Object instances to mock
* @param recordPrivateCalls If true, enables private call recording
*/
inline fun mockkObject(vararg objects: Any, recordPrivateCalls: Boolean = false)
/**
* Cancels object mocks
* @param objects Objects to unmock
*/
inline fun unmockkObject(vararg objects: Any)
/**
* Mocks objects for the duration of a block
* @param objects Objects to mock
* @param recordPrivateCalls If true, enables private call recording
* @param block Block to execute with object mocking active
*/
inline fun mockkObject(
vararg objects: Any,
recordPrivateCalls: Boolean = false,
block: () -> Unit
)Usage Examples:
// Kotlin object to mock
object DatabaseConfig {
fun getConnectionString(): String = "real://connection"
fun getMaxConnections(): Int = 10
private fun validateConfig(): Boolean = true
}
// Mock the object
mockkObject(DatabaseConfig)
// Stub object methods
every { DatabaseConfig.getConnectionString() } returns "mock://connection"
every { DatabaseConfig.getMaxConnections() } returns 5
// Use the object - methods are now mocked
val connectionString = DatabaseConfig.getConnectionString() // "mock://connection"
val maxConnections = DatabaseConfig.getMaxConnections() // 5
// Verify object method calls
verify { DatabaseConfig.getConnectionString() }
verify { DatabaseConfig.getMaxConnections() }
// Clean up
unmockkObject(DatabaseConfig)
// Scoped object mocking
mockkObject(DatabaseConfig) {
every { DatabaseConfig.getConnectionString() } returns "scoped://mock"
val result = DatabaseConfig.getConnectionString() // "scoped://mock"
}
// Object mock automatically cleaned up after block
// Mock with private call recording
mockkObject(DatabaseConfig, recordPrivateCalls = true)
// Now private methods can be verifiedMock class constructors to return singleton instances.
/**
* Mocks constructors of the specified classes
* @param classes Classes whose constructors should be mocked
* @param recordPrivateCalls If true, enables private call recording
* @param localToThread If true, mocking is local to current thread
*/
inline fun mockkConstructor(
vararg classes: KClass<*>,
recordPrivateCalls: Boolean = false,
localToThread: Boolean = false
)
/**
* Cancels constructor mocks
* @param classes Classes to unmock
*/
inline fun unmockkConstructor(vararg classes: KClass<*>)
/**
* Mocks constructors for the duration of a block
* @param classes Classes whose constructors to mock
* @param recordPrivateCalls If true, enables private call recording
* @param localToThread If true, mocking is local to current thread
* @param block Block to execute with constructor mocking active
*/
inline fun mockkConstructor(
vararg classes: KClass<*>,
recordPrivateCalls: Boolean = false,
localToThread: Boolean = false,
block: () -> Unit
)Usage Examples:
// Class to mock constructor for
class Logger(private val name: String) {
fun log(message: String) = println("[$name] $message")
fun error(message: String) = println("[$name] ERROR: $message")
}
class Service {
private val logger = Logger("Service") // This constructor call will be mocked
fun doWork() {
logger.log("Starting work")
logger.log("Work completed")
}
}
// Mock Logger constructor
mockkConstructor(Logger::class)
// Stub methods on the constructor-created instance
every { anyConstructed<Logger>().log(any()) } just Runs
every { anyConstructed<Logger>().error(any()) } just Runs
// Use the class - constructor creates mocked instances
val service = Service()
service.doWork() // Logger calls are now mocked
// Verify constructor calls and method calls
verify { anyConstructed<Logger>().log("Starting work") }
verify { anyConstructed<Logger>().log("Work completed") }
// Clean up
unmockkConstructor(Logger::class)
// Scoped constructor mocking
mockkConstructor(Logger::class) {
every { anyConstructed<Logger>().log(any()) } just Runs
val service = Service()
service.doWork() // Constructor mocked within this block
}
// Constructor mock automatically cleaned up after blockAdditional mocking capabilities available on JVM platform.
/**
* Mocks static functions by KFunction reference (JVM only)
* @param functions Static functions to mock
*/
fun mockkStatic(vararg functions: KFunction<*>)
/**
* Mocks static properties by KProperty reference (JVM only)
* @param properties Static properties to mock
*/
fun mockkStatic(vararg properties: KProperty<*>)
/**
* Extension property to get declaring class of top-level function (JVM only)
*/
val KFunction<*>.declaringKotlinFile: KClass<*>Usage Examples:
// Top-level functions and properties
fun topLevelFunction(): String = "real value"
val topLevelProperty: String = "real property"
// Mock specific functions by reference (JVM only)
mockkStatic(::topLevelFunction)
every { topLevelFunction() } returns "mocked value"
// Use the function
val result = topLevelFunction() // "mocked value"
// Get declaring class of top-level function
val declaringClass = ::topLevelFunction.declaringKotlinFileFunctions for managing and cleaning up mocks.
/**
* Clears static mocks
* @param classes Classes to clear
* @param answers Clear stubbed answers (default: true)
* @param recordedCalls Clear recorded calls (default: true)
* @param childMocks Clear child mocks (default: true)
*/
inline fun clearStaticMockk(
vararg classes: KClass<*>,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true
)
/**
* Clears constructor mocks
* @param classes Classes to clear
* @param answers Clear stubbed answers (default: true)
* @param recordedCalls Clear recorded calls (default: true)
* @param childMocks Clear child mocks (default: true)
*/
inline fun clearConstructorMockk(
vararg classes: KClass<*>,
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true
)
/**
* Cancels all mocks (objects, static, constructor)
*/
inline fun unmockkAll()
/**
* Clears all mocks with comprehensive filtering options
* @param answers Clear stubbed answers (default: true)
* @param recordedCalls Clear recorded calls (default: true)
* @param childMocks Clear child mocks (default: true)
* @param regularMocks Clear regular mocks (default: true)
* @param objectMocks Clear object mocks (default: true)
* @param staticMocks Clear static mocks (default: true)
* @param constructorMocks Clear constructor mocks (default: true)
* @param currentThreadOnly Only clear mocks for current thread (default: false)
*/
inline fun clearAllMocks(
answers: Boolean = true,
recordedCalls: Boolean = true,
childMocks: Boolean = true,
regularMocks: Boolean = true,
objectMocks: Boolean = true,
staticMocks: Boolean = true,
constructorMocks: Boolean = true,
currentThreadOnly: Boolean = false
)Usage Examples:
// Setup various mocks
mockkStatic(FileUtils::class)
mockkObject(DatabaseConfig)
mockkConstructor(Logger::class)
// Clear specific mock types
clearStaticMockk(FileUtils::class)
clearConstructorMockk(Logger::class)
// Clear all mocks
unmockkAll()
// Clear all mocks with specific filtering
clearAllMocks(
answers = true,
recordedCalls = true,
staticMocks = true,
constructorMocks = false // Keep constructor mocks
)Verification functions specific to special mocking types.
/**
* Reference to any constructed instance for verification
*/
fun <T : Any> anyConstructed(): T
/**
* Verify calls on constructed instances
*/
fun <T : Any> verifyConstructed(verifyBlock: MockKVerificationScope.() -> Unit)Usage Examples:
mockkConstructor(Logger::class)
// Stub constructor-created instances
every { anyConstructed<Logger>().log(any()) } just Runs
// Create and use class that creates Logger instances
val service = Service()
service.doWork()
// Verify on any constructed instance
verify { anyConstructed<Logger>().log("Starting work") }
// Alternative verification syntax
verifyConstructed<Logger> {
log("Starting work")
log("Work completed")
}Constructor mocking can be made thread-local for concurrent testing scenarios.
/**
* Thread-local constructor mocking
* @param localToThread If true, mocking only affects current thread
*/
inline fun mockkConstructor(
vararg classes: KClass<*>,
localToThread: Boolean = true
)Usage Examples:
// Thread-local constructor mocking
mockkConstructor(Logger::class, localToThread = true)
// Mock only affects current thread
every { anyConstructed<Logger>().log(any()) } just Runs
// Other threads will use real constructors
thread {
val service = Service() // Uses real Logger constructor
service.doWork()
}
// Current thread uses mocked constructor
val service = Service() // Uses mocked Logger constructor
service.doWork()Install with Tessl CLI
npx tessl i tessl/maven-io-mockk--mockk