Mocking #

Mocking start with one call, the mockk function. This function takes in a class and returns a fake version of it, where all functions are present but will throw when called.

import io.mockk.mockk

val mockedFile = mockk<File>()
Stub out behaviour
Using every and returns to define behaviour.
Verify that functions were called
Using verify to check that a function was used.
Automatically stub by relaxing
How to change the default mockk result with relaxed.
Spy on existing classes
Using spyk to mix mocks and real classes.
Coroutines and suspend functions
Using coEvery, coVerify, and more to mock coroutines.
Mock constructors in code you don't own
Advanced mocking with mockkConstructor.
Mock singleton objects and static methods
Advanced static mocking with mockkStatic and mockkObject.
Mock top-level and extension functions
Mocking top-level functions with mockkStatic.
Clear state
(TODO) Clearing the state of a mock.
Create many mocks quickly with annotations
The @MockK and @SpyK shortcuts.
Chain mocks into hierarchies
(TODO) Building a mock with less code using lambdas.
Create more complicated answers for stubs
Using answers when returns just isn’t enough.
Buy Me a Coffee at