Solution: Mocking library

import org.junit.Test import java.lang.reflect.Method import java.lang.reflect.Proxy import kotlin.reflect.KClass import kotlin.test.assertEquals import kotlin.test.assertNotNull class MockRegistry { inline fun <reified T : Any> mock(): T = mock(T::class) private var recording = false private var bodyToStore: (() -> Any?)? = null private var handlers = mutableMapOf<Record, () -> Any?>() inline fun <reified T: Any> mock(): T = mock(T::class.java) fun <T : Any> mock(classRef: KClass<T>): T { val proxy = Any() return Proxy.newProxyInstance( classRef.java.classLoader, arrayOf(classRef.java) ) { _, method, args -> val record = Record(proxy, method, args?.toList()) if (recording) { handlers[record] = checkNotNull(bodyToStore) throw RecordedCorrectlyException() } else { checkNotNull(handlers[record]) { "No recording..." } .invoke() } } as T } fun <T> setBody(functionCall: () -> T, body: () -> T) { try { recording = true this.bodyToStore = body functionCall() } catch (e: RecordedCorrectlyException) { // no-op } finally { recording = false this.bodyToStore = null } } fun <T> setReturnValue(functionCall: () -> T, value: T) { setBody(functionCall) { value } } class RecordedCorrectlyException : RuntimeException() data class Record( val proxy: Any, val method: Method, val arguments: List<Any?>?, ) }