Getting started All you need to get started is just to add a dependency to MockK library. Gradle/Maven dependency Approach Instruction testImplementation "io.mockk:mockk:${mockkVersion}" (Kotlin DSL) testImplementation("io.mockk:mockk:${mockkVersion}") <dependency> <groupId>io.mockk</groupId> <artifactId>mockk-jvm</artifactId> <version>${mockkVersion}</version>…






Getting started
All you need to get started is just to add a dependency to MockK library.
Gradle/Maven dependency
ApproachInstruction
testImplementation "io.mockk:mockk:${mockkVersion}"
(Kotlin DSL)
testImplementation("io.mockk:mockk:${mockkVersion}")
<dependency>
<groupId>io.mockk</groupId>
<artifactId>mockk-jvm</artifactId>
<version>${mockkVersion}</version>
<scope>test</scope>
</dependency>
Unit
testImplementation "io.mockk:mockk-android:${mockkVersion}"
testImplementation "io.mockk:mockk-agent:${mockkVersion}"
Instrumented
androidTestImplementation "io.mockk:mockk-android:${mockkVersion}"
androidTestImplementation "io.mockk:mockk-agent:${mockkVersion}"
DSL examples
Simplest example. By default mocks are strict, so you need to provide some behaviour.
kotlin
val car = mockk()
every { car.drive(Direction.NORTH) } returns Outcome.OK
car.drive(Direction.NORTH) // returns OK
verify { car.drive(Direction.NORTH) }
confirmVerified(car)
See the "Features" section below for more detailed examples.
BDD style (optional)
For teams using Behavior-Driven Development, MockK provides BDD-style aliases
gradle
testImplementation "io.mockk:mockk:${mockkVersion}"
testImplementation "io.mockk:mockk-bdd:${mockkVersion}"
gradle
androidTestImplementation "io.mockk:mockk-android:${mockkVersion}"
androidTestImplementation "io.mockk:mockk-bdd-android:${mockkVersion}"
BDD aliases
| Standard MockK | BDD style |
|----------------|-----------|
| every { ... } | given { ... } |
| coEvery { ... } | coGiven { ... } |
| verify { ... } | then { ... } |
| coVerify { ... } | coThen { ... } |
Spring support
* springmockk introduced in official Spring Boot Kotlin tutorial
Quarkus support
* quarkus-mockk adds support for mocking beans in Quarkus. Documentation can be found here
Kotlin version support
From version 1.13.0 MockK supports Kotlin 1.4 and higher
Known issues
- PowerMock needs a workaround to run together with MockK #79. (not sure after workaround if it is generally usable or not, please somebody report it)
- Inline functions cannot be mocked: see the discussion on this issue
- Spies,
mockkStaticmay not work on JDK 16+;InaccessibleObjectException/IllegalAccessException: [read more here](doc/md/jdk16-access-exceptions.md) - Using a spy with a suspending function will give unexpected test results
- auto-gen TOC:
Examples, guides & articles
Kotlin Academy articles
Check the series of articles "Mocking is not rocket science" at Kt. Academy describing MockK from the very basics of mocking up to description of all advanced features.
- Basics
- Expected behavior and behavior verification
- MockK features
- MockK advanced features
- Testing Quarkus with Kotlin, JUnit and MockK
- Unraveling MockK's black magic(EN, translation)
- Mockk Guidebook
- “Kotlin Unit Testing with Mockk” by Marco Cattaneo
- (Video) Use verify in MockK to validate function calls on mocked object
- Testing With MockK paid course on raywenderlich.com
- TDD for Android video tutorial part 1, part 2 by Ryan Kay
- (Video)Android Developer Live Coding #13: Unit Testing with Mockk, Coroutines, Test Driven Development
- KotlinConf 2018 - Best Practices for Unit Testing in Kotlin by Philipp Hauer
- kotlin-fullstack-sample uses MockK project covered with tests
- DZone article
- Habrahabr article (RU)
- Mocking in Kotlin with MockK - Yannick De Turck
- How does MockK work internally? - Sagar Malhotra
Japanese guides and articles
- Documentation translation to Japanese - Unraveling MockK's black magic / MockKの「黒魔術」を解明する (JP, but readable through chrome translator)Chinese guides and articles
- 用 Kotlin + Mockito 寫單元測試會碰到什麼問題? - MockK 功能介紹:mockk, every, Annotation, verify - MockK 功能介紹:Relaxed Mocks, 再談 Verify, Capture - 如何測試 Static Method, SingletonKorean guides and articles
- Documentation translation to Korean - MockK의 흑마술을 파헤치자!Features
Annotations
You can use annotations to simplify the creation of mock objects:
kotlin
class TrafficSystem {
lateinit var car1: Car
lateinit var car2: Car
lateinit var car3: Car
}
class CarTest {
@MockK
lateinit var car1: Car
@RelaxedMockK
lateinit var car2: Car
@MockK(relaxUnitFun = true)
lateinit var car3: Car
@SpyK
var car4 = Car()
@InjectMockKs
var trafficSystem = TrafficSystem()
@Before
fun setUp() = MockKAnnotations.init(this, relaxUnitFun = true) // turn relaxUnitFun on for all mocks
@Test
fun calculateAddsValues1() {
// ... use car1, car2, car3 and car4
}
}
Injection first tries to match properties by name, then by class or superclass.
Check the lookupType parameter for customization.
Properties are injected even if private is applied. Constructors for injection are selected from the biggest
number of arguments to lowest.
@InjectMockKs by default injects only lateinit vars or vars that are not assigned.
To change this, use overrideValues = true. This would assign the value even if it is already initialized somehow.
To inject vals, use injectImmutable = true. For a shorter notation use @OverrideMockKs which does the same as@InjectMockKs by default, but turns these two flags on.
@InjectMockKs dependency order
If multiple @InjectMockKs properties depend on each other via constructor parameters, initialization order matters.
By default, MockK processes them in reflection order; to resolve dependencies deterministically, enable dependency
order:
kotlin
@Before
fun setUp() = MockKAnnotations.init(this, useDependencyOrder = true)
This applies a topological sort across @InjectMockKs and throws MockKException on circular dependencies.
Enabling useDependencyOrder adds an approximate 3-5% performance overhead during initialization.
JUnit4
JUnit 4 exposes a rule-based API to allow for some automation following the test lifecycle. MockK includes a rule which uses this to set up and tear down your mocks without needing to manually call MockKAnnotations.init(this). Example:
kotlin
class CarTest {
@get:Rule
val mockkRule = MockKRule(this)
@MockK
lateinit var car1: Car
@RelaxedMockK
lateinit var car2: Car
@Test
fun something() {
every { car1.drive() } just runs
every { car2.changeGear(any()) } returns true
// etc
}
}
JUnit5
In JUnit5 you can use MockKExtension to initialize your mocks.
kotlin
@ExtendWith(MockKExtension::class)
class CarTest {
@MockK
lateinit var car1: Car
@RelaxedMockK
lateinit var car2: Car
@MockK(relaxUnitFun = true)
lateinit var car3: Car
@SpyK
var car4 = Car()
@Test
fun calculateAddsValues1() {
// ... use car1, car2, car3 and car4
}
}
Additionally, it adds the possibility to use @MockK and @RelaxedMockK on test function parameters:
kotlin
@Test
fun calculateAddsValues1(@MockK car1: Car, @RelaxedMockK car2: Car) {
// ... use car1 and car2
}
Finally, this extension will call unmockkAll and clearAllMocks in a @AfterAll callback, ensuring your test environment is clean after
each test class execution.
You can disable this behavior by adding the @MockKExtension.KeepMocks annotation to your class or globally by setting
the mockk.junit.extension.keepmocks=true property.
(Since v1.13.11)
Alternatively, since clearAllMocks by default (currentThreadOnly=false) is not thread-safe, if you need to run test in parallel you can add theMockKExtension.RequireParallelTesting annotation to your class or set the mockk.junit.extension.requireParallelTesting=true
property to disable calling it in the @AfterAll callback.
If clearAllMocks is explicitly called, you can supply clearAllMocks(currentThreadOnly = true) so that it only clears mocks created within the same thread (since v1.13.12).
Automatic verification confirmation
You can make sure that all stubbed methods are actually verified by also annotating your test class with @MockKExtension.ConfirmVerification.
This will internally call confirmVerified on all mocks after each test, to make sure there are no unnecessary stubbings.
Please note that this behavior may not work as expected when running tests in your IDE, as it is Gradle who takes care of handling the exception being thrown when these confirmVerified calls fail.
Automatic unnecessary stubbing check
You can make sure that all stubbed methods are useful - used at least once - by also annotating your test class with @MockKExtension.CheckUnnecessaryStub.
This will internally call checkUnnecessaryStub on all mocks after each test, to make sure there are no unnecessary stubbings.
Declarative enabling of dependency order
You can enable topological dependency resolution of @InjectMockKs by also annotating your test class with @MockKExtension.UseDependencyOrder.
This will internally process each test instance of the annotated class with MockKAnnotations.init(useDependencyOrder==true).
Spy
Spies allow you to mix mocks and real objects.
kotlin
val car = spyk(Car()) // or spyk() to call the default constructor
car.drive(Direction.NORTH) // returns whatever the real function of Car returns
verify { car.drive(Direction.NORTH) }
confirmVerified(car)
Note 1: the spy object is a copy of the passed object.
Note 2: there is a known issue if using a spy with a suspending function: https://github.com/mockk/mockk/issues/554
Relaxed mock
A relaxed mock is the mock that returns some simple value for all functions.
This allows you to skip specifying behavior for each case, while still stubbing things you need.
For reference types, chained mocks are returned.
kotlin
val car = mockk(relaxed = true)
car.drive(Direction.NORTH) // returns null
verify { car.drive(Direction.NORTH) }
confirmVerified(car)
Note: relaxed mocking is working badly with generic return types. A class cast exception is usually thrown in this case.
Opt for stubbing manually in the case of a generic return type.
Workaround:
kotlin
val func = mockk<() -> Car>(relaxed = true) // in this case invoke function has generic return type
// this line is workaround, without it the relaxed mock would throw a class cast exception on the next line
every { func() } returns Car() // or you can return mockk() for example
func()
Partial mocking
Sometimes, you need to stub some functions, but still call the real method on others, or on specific arguments.
This is possible by passing callOriginal() to answers, which works for both relaxed and non-relaxed mocks.
kotlin
class Adder {
fun addOne(num: Int) = num + 1
}
val adder = mockk()
every { adder.addOne(any()) } returns -1
every { adder.addOne(3) } answers { callOriginal() }
assertEquals(-1, adder.addOne(2))
assertEquals(4, adder.addOne(3)) // original function is called
Mock relaxed for functions returning Unit
If you want Unit-returning functions to be relaxed, you can use relaxUnitFun = true as an argument to the mockk function,@MockKannotation or MockKAnnotations.init function.
kotlin
mockk(relaxUnitFun = true)
Annotation:
kotlin
@MockK(relaxUnitFun = true)
lateinit var mock1: ClassBeingMocked
init {
MockKAnnotations.init(this)
}
MockKAnnotations.init:
kotlin
@MockK
lateinit var mock2: ClassBeingMocked
init {
MockKAnnotations.init(this, relaxUnitFun = true)
}
Object mocks
Objects can be turned into mocks in the following way:
```kotlin
object ObjBeingMocked {
…
-
mockk
mocking library for Kotlin
Kotlin ★ 5.7k 7d agoExplain → -
decembrist-kotlin2js-reflection ⑂
Plugin for kotlin js annotation processing
Kotlin ★ 1 7y agoExplain →
No repos match these filters.