Kotlin MockK Usage (Official Documentation Translation)

MockK is a Kotlin mock library for writing test code. This document is an English translation of the Korean page based on the official documentation.

Getting Started

MockK is a Kotlin mock library for writing test code. This document is based on the official documentation.

Installation

To get started, add a dependency on the MockK library.

Approach Command
Gradle testImplementation "io.mockk:mockk:{version}"
Gradle (Kotlin DSL) testImplementation("io.mockk:mockk:{version}")
Maven <dependency> <groupId>io.mockk</groupId> <artifactId>mockk</artifactId> <version>{version}</version> <scope>test</scope> </dependency>
Unit testImplementation "io.mockk:mockk:{version}"
Instrumented androidTestImplementation "io.mockk:mockk-android:{version}"
Common multiplatform testImplementation "io.mockk:mockk-common:{version}"

{version} corresponds to:

  • Kotlin 1.3+ and Coroutines 1.0+
  • Kotlin 1.2 compatible versions

DSL Examples

This is the simplest example. By default, mock objects are strict, so you must provide some behavior.

val car = mockk<Car>()

every { car.drive(Direction.NORTH) } returns Outcome.OK

car.drive(Direction.NORTH) // returns OK

verify { car.drive(Direction.NORTH) }

confirmVerified(car)

Annotations

Annotations can simplify mock object creation.

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) // turns on relaxUnitFun for all mocks

  @Test
  fun calculateAddsValues1() {
      // ... use car1, car2, car3 and car4
  }
}

Injection first matches properties by name, then by class or superclass. Check the lookupType parameter for custom behavior.

Properties are injected even when they are private. Injection constructors are selected from the largest number of arguments to the smallest.

By default, @InjectMockKs injects only lateinit var or unassigned var properties. To change this, use overrideValues = true; this assigns values even when they have already been initialized somehow. To inject val, use injectImmutable = true. For a shorter form, use @OverrideMockKs, which behaves like @InjectMockKs by default but enables both flags.

JUnit5

JUnit5 can initialize mocks using MockKExtension.

@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
  }
}

It also adds the ability to use @MockK and @RelaxedMockK on test function parameters.

@Test
fun calculateAddsValues1(@MockK car1: Car, @RelaxedMockK car2: Car) {
  // ... use car1 and car2
}

Spy

Spies can mix mocks and real objects.

val car = spyk(Car()) // or spyk<Car>() to call the default constructor

car.drive(Direction.NORTH) // returns the real function returned by Car

verify { car.drive(Direction.NORTH) }

confirmVerified(car)

Note: A spy object is a copy of the object passed in.

Relaxed mock

A relaxed mock returns simple values for all functions. This lets you stub only what you need while omitting behavior definitions for each case. For reference types, chained mocks are returned.

val car = mockk<Car>(relaxed = true)

car.drive(Direction.NORTH) // returns null

verify { car.drive(Direction.NORTH) }

confirmVerified(car)

Note: When using a relaxed mock, generic return values do not work well. Usually, a class cast exception is thrown in this case. If the return value is generic, specify the stub manually.

Workaround:

val func = mockk<() -> Car>(relaxed = true) // in this case invoke has a generic return value

// this line is the workaround. Without it, the relaxed mock throws a class cast exception on the next line
every { func() } returns Car() // or return mockk(), for example

func()

Relaxed mock for functions returning Unit

If you want to relax functions that return Unit, use relaxUnitFun = true as an argument to the mockk function, the @MockK annotation, or the MockKAnnotations.init function.

mockk function:

mockk<MockCls>(relaxUnitFun = true)

@MockK annotation:

@MockK(relaxUnitFun = true)
lateinit var mock1: RurfMockCls
init {
    MockKAnnotations.init(this)
}

MockKAnnotations.init function:

@MockK
lateinit var mock2: RurfMockCls
init {
    MockKAnnotations.init(this, relaxUnitFun = true)
}

Object mocks

Objects can be converted to mocks as follows.

object MockObj {
  fun add(a: Int, b: Int) = a + b
}

mockkObject(MockObj) // applies to the object mock

assertEquals(3, MockObj.add(1, 2))

every { MockObj.add(1, 2) } returns 55

assertEquals(55, MockObj.add(1, 2))

Use unmockkAll or unmockkObject to cancel it.

@Before
fun beforeTests() {
    mockkObject(MockObj)
    every { MockObj.add(1,2) } returns 55
}

@Test
fun willUseMockBehaviour() {
    assertEquals(55, MockObj.add(1,2))
}

@After
fun afterTests() {
    unmockkAll()
    // or unmockkObject(MockObj)
}

Despite Kotlin language restrictions, you can create a new instance of an object when needed for test logic.

val newObjectMock = mockk<MockObj>()

Class mock

Sometimes you need a mock of a class. In that case, use mockkClass.

val car = mockkClass(Car::class)

every { car.drive(Direction.NORTH) } returns Outcome.OK

car.drive(Direction.NORTH) // returns OK

verify { car.drive(Direction.NORTH) }

Enumeration mocks

Enums can be mocked using mockkObject.

enum class Enumeration(val goodInt: Int) {
    CONSTANT(35),
    OTHER_CONSTANT(45);
}

mockkObject(Enumeration.CONSTANT)
every { Enumeration.CONSTANT.goodInt } returns 42
assertEquals(42, Enumeration.CONSTANT.goodInt)

Constructor mocks

Sometimes, especially for code you do not own, you need to mock newly created objects. The following configuration is provided for that.

class MockCls {
  fun add(a: Int, b: Int) = a + b
}

mockkConstructor(MockCls::class)

every { anyConstructed<MockCls>().add(1, 2) } returns 4

assertEquals(4, MockCls().add(1, 2)) // note that a new object is created

verify { anyConstructed<MockCls>().add(1, 2) }

The basic idea is that right after the constructor of the mocked class runs, the object becomes a constructed mock. The mock behavior for such objects is connected to a special prototype mock represented by anyConstructed<MockCls>(). There is one instance of this prototype mock per class. Call recording also happens on the prototype mock. If a function is not specified, the original function runs.

Partial argument matching

You can mix normal arguments and matchers.

val car = mockk<Car>()

every { 
  car.recordTelemetry(
    speed = more(50),
    direction = Direction.NORTH, // "eq()" is used here
    lat = any(),
    long = any()
  )
} returns Outcome.RECORDED

obj.recordTelemetry(60, Direction.NORTH, 51.1377382, 17.0257142)

verify { obj.recordTelemetry(60, Direction.NORTH, 51.1377382, 17.0257142) }

confirmVerified(obj)

Chained calls

You can stub call chains.

val car = mockk<Car>()

every { car.door(DoorType.FRONT_LEFT).windowState() } returns WindowState.UP

car.door(DoorType.FRONT_LEFT) // returns Door chained mock
car.door(DoorType.FRONT_LEFT).windowState() // returns WindowState.UP

verify { car.door(DoorType.FRONT_LEFT).windowState() }

confirmVerified(car)

Note: If a function’s return type is generic, information about the actual type is erased. Extra information is needed for chained calls to work. In most cases, the framework catches the cast exception and performs autohinting. If needed explicitly, use hint before the next call.

every { obj.op2(1, 2).hint(Int::class).op1(3, 4) } returns 5

Hierarchical mocking

Since version 1.9.1, mock hierarchies can be chained.

interface AddressBook {
    val contacts: List<Contact>
}

interface Contact {
    val name: String
    val telephone: String
    val address: Address
}

interface Address {
    val city: String
    val zip: String
}

val addressBook = mockk<AddressBook> {
    every { contacts } returns listOf(
        mockk {
            every { name } returns "John"
            every { telephone } returns "123-456-789"
            every { address.city } returns "New-York"
            every { address.zip } returns "123-45"
        },
        mockk {
            every { name } returns "Alex"
            every { telephone } returns "789-456-123"
            every { address } returns mockk {
                every { city } returns "Wroclaw"
                every { zip } returns "543-21"
            }
        }
    )
}

Capturing

Arguments can be captured with CapturingSlot or MutableList.

val car = mockk<Car>()

val slot = slot<Double>()
val list = mutableListOf<Double>()

every {
  obj.recordTelemetry(
    speed = capture(slot),
    direction = Direction.NORTH
  )
} answers {
  println(slot.captured)

  Outcome.RECORDED
}


every {
  obj.recordTelemetry(
    speed = capture(list),
    direction = Direction.SOUTH
  )
} answers {
  println(list.captured())

  Outcome.RECORDED
}

obj.recordTelemetry(speed = 15, direction = Direction.NORTH) // prints 15
obj.recordTelemetry(speed = 16, direction = Direction.SOUTH) // prints 16

verify(exactly = 2) { obj.recordTelemetry(speed = or(15, 16), direction = any()) }

confirmVerified(obj)

Verification atLeast, atMost, or exactly times

Call counts can be checked with the atLeast, atMost, or exactly parameters.

val car = mockk<Car>(relaxed = true)

car.accelerate(fromSpeed = 10, toSpeed = 20)
car.accelerate(fromSpeed = 10, toSpeed = 30)
car.accelerate(fromSpeed = 20, toSpeed = 30)

// all pass
verify(atLeast = 3) { car.accelerate(allAny()) }
verify(atMost  = 2) { car.accelerate(fromSpeed = 10, toSpeed = or(20, 30)) }
verify(exactly = 1) { car.accelerate(fromSpeed = 10, toSpeed = 20) }
verify(exactly = 0) { car.accelerate(fromSpeed = 30, toSpeed = 10) } // means it was not called

confirmVerified(car)

Verification order

  • verifyAll checks that all calls were made without checking order.
  • verifySequence checks that calls were made in the specified sequence.
  • verifyOrder checks whether calls happened in a specific order.
  • wasNot Called checks that a mock or list of mocks was not called at all.
class MockedClass {
    fun sum(a: Int, b: Int) = a + b
}

val obj = mockk<MockedClass>()
val slot = slot<Int>()

every {
    obj.sum(any(), capture(slot))
} answers {
    1 + firstArg<Int>() + slot.captured
}

obj.sum(1, 2) // returns 4
obj.sum(1, 3) // returns 5
obj.sum(2, 2) // returns 5

verifyAll {
    obj.sum(1, 3)
    obj.sum(1, 2)
    obj.sum(2, 2)
}

verifySequence {
    obj.sum(1, 2)
    obj.sum(1, 3)
    obj.sum(2, 2)
}

verifyOrder {
    obj.sum(1, 2)
    obj.sum(2, 2)
}

val obj2 = mockk<MockedClass>()
val obj3 = mockk<MockedClass>()
verify {
    listOf(obj2, obj3) wasNot Called
}

confirmVerified(obj)

Verification confirmation

To double-check that all calls have been verified by a verify... construct, use confirmVerified.

confirmVerified(mock1, mock2)

Because these verification methods already cover all verified calls, using verifySequence and verifyAll together does not make much sense.

If some calls remain unverified, an exception is thrown.

Some calls can be excluded from this confirmation. See the next section for details.

val car = mockk<Car>()

every { car.drive(Direction.NORTH) } returns Outcome.OK
every { car.drive(Direction.SOUTH) } returns Outcome.OK

car.drive(Direction.NORTH) // returns OK
car.drive(Direction.SOUTH) // returns OK

verify {
    car.drive(Direction.SOUTH)
    car.drive(Direction.NORTH)
}

confirmVerified(car) // confirms that all calls were verified

Recording exclusions

To exclude less important calls from recording, use excludeRecords.

excludeRecords { mock.operation(any(), 5) }

All matching calls are excluded from recording. This is useful when using comprehensive verification such as verifyAll, verifySequence, or confirmVerified.

val car = mockk<Car>()

every { car.drive(Direction.NORTH) } returns Outcome.OK
every { car.drive(Direction.SOUTH) } returns Outcome.OK

excludeRecords { car.drive(Direction.SOUTH) }

car.drive(Direction.NORTH) // returns OK
car.drive(Direction.SOUTH) // returns OK

verify {
    car.drive(Direction.NORTH)
}

confirmVerified(car) // only car.drive(Direction.NORTH) needs confirmation because car.drive(Direction.SOUTH) was excluded

Verification timeout

To verify concurrent work, use timeout = xxx.

mockk<MockCls> {
    every { sum(1, 2) } returns 4

    Thread {
        Thread.sleep(2000)
        sum(1, 2)
    }.start()

    verify(timeout = 3000) { sum(1, 2) }
}

This waits until verification passes, the timeout is reached, or one of the states occurs.

Returning Unit

If a function returns Unit, use just Runs.

class MockedClass {
    fun sum(a: Int, b: Int): Unit {
        println(a + b)
    }
}

val obj = mockk<MockedClass>()

every { obj.sum(any(), 3) } just Runs

obj.sum(1, 1)
obj.sum(1, 2)
obj.sum(1, 3)

verify {
    obj.sum(1, 1)
    obj.sum(1, 2)
    obj.sum(1, 3)
}

Coroutines

To mock coroutines, add another dependency to the support library.

Gradle:

testCompile "org.jetbrains.kotlinx:kotlinx-coroutines-core:x.x"

Maven:

<dependency>
    <groupId>org.jetbrains.kotlinx</groupId>
    <artifactId>kotlinx-coroutines-core</artifactId>
    <version>x.x</version>
    <scope>test</scope>
</dependency>

Then suspend functions can be mocked using coEvery, coVerify, coMatch, coAssert, coRun, coAnswers, or coInvoke.

val car = mockk<Car>()

coEvery { car.drive(Direction.NORTH) } returns Outcome.OK

car.drive(Direction.NORTH) // returns OK

coVerify { car.drive(Direction.NORTH) }

Extension functions

There are three cases for extension functions.

  • Class-wide
  • Object-wide
  • Module-wide

For objects and classes, you can usually mock extension functions simply by mocking.

data class Obj(val value: Int)

class Ext {
    fun Obj.extensionFunc() = value + 5
}

with(mockk<Ext>()) {
    every {
        Obj(5).extensionFunc()
    } returns 11

    assertEquals(11, Obj(5).extensionFunc())

    verify {
        Obj(5).extensionFunc()
    }
}

To mock a module-wide extension function, build it with mockkStatic(...) using the module class name as an argument. For example, for module File.kt in package pkg, use "pkg.FileKt".

data class Obj(val value: Int)

// declared in File.kt in the "pkg" package
fun Obj.extensionFunc() = value + 5

mockkStatic("pkg.FileKt")

every {
    Obj(5).extensionFunc()
} returns 11

assertEquals(11, Obj(5).extensionFunc())

verify {
    Obj(5).extensionFunc()
}

If @JvmName is used, specify that class name.

KHttp.kt:

@file:JvmName("KHttp")

package khttp
// ... KHttp code 

Test code:

mockkStatic("khttp.KHttp")

Sometimes you need to know more detail to mock an extension function. For example, the File.endsWith() extension has a completely unpredictable classname.

mockkStatic("kotlin.io.FilesKt__UtilsKt")
every { File("abc").endsWith(any<String>()) } returns true
println(File("abc").endsWith("abc"))

This is unpredictable standard Kotlin behavior. Use [Tools]-> [Kotlin]->[Show Kotlin Bytecode] or inspect .class files in the JAR archive to find these names.

Varargs

Since version 1.9.1, more advanced vararg handling is available.

    interface ClsWithManyMany {
        fun manyMany(vararg x: Any): Int
    }

    val obj = mockk<ClsWithManyMany>()

    every { obj.manyMany(5, 6, *varargAll { it == 7 }) } returns 3

    println(obj.manyMany(5, 6, 7)) // 3
    println(obj.manyMany(5, 6, 7, 7)) // 3
    println(obj.manyMany(5, 6, 7, 7, 7)) // 3

    every { obj.manyMany(5, 6, *anyVararg(), 7) } returns 4

    println(obj.manyMany(5, 6, 1, 7)) // 4
    println(obj.manyMany(5, 6, 2, 3, 7)) // 4
    println(obj.manyMany(5, 6, 4, 5, 6, 7)) // 4

    every { obj.manyMany(5, 6, *varargAny { nArgs > 5 }, 7) } returns 5

    println(obj.manyMany(5, 6, 4, 5, 6, 7)) // 5
    println(obj.manyMany(5, 6, 4, 5, 6, 7, 7)) // 5

    every {
        obj.manyMany(5, 6, *varargAny {
            if (position < 3) it == 3 else it == 4
        }, 7)
    } returns 6

    println(obj.manyMany(5, 6, 3, 4, 7)) // 6
    println(obj.manyMany(5, 6, 3, 4, 4, 7)) // 6

Private functions mocking / dynamic calls

If you need to mock private functions, you can do it through dynamic calls.

class Car {
    fun drive() = accelerate()

    private fun accelerate() = "going faster"
}

val mock = spyk<Car>(recordPrivateCalls = true)

every { mock["accelerate"]() } returns "going not so fast"

assertEquals("going not so fast", mock.drive())

verifySequence {
    mock.drive()
    mock["accelerate"]()
}

To verify private calls, create the spyk with recordPrivateCalls = true.

The same dynamic call syntax can also be used to get and set properties.

val mock = spyk(Team(), recordPrivateCalls = true)

every { mock getProperty "speed" } returns 33
every { mock setProperty "acceleration" value less(5) } just runs
every { mock invokeReturnsUnit "privateMethod" } just runs
every { mock invoke "openDoor" withArguments listOf("left", "rear") } returns "OK"

verify { mock getProperty "speed" }
verify { mock setProperty "acceleration" value less(5) }
verify { mock invoke "openDoor" withArguments listOf("left", "rear") }

Property backing fields

You can access backing field properties through fieldValue and use value for the value being set.

Note: In the following example, propertyType is used to specify the fieldValue type. This is needed because getter types can be captured automatically. Use nullablePropertyType to specify a nullable type.

val mock = spyk(MockCls(), recordPrivateCalls = true)

every { mock.property } answers { fieldValue + 6 }
every { mock.property = any() } propertyType Int::class answers { fieldValue += value }
every { mock getProperty "property" } propertyType Int::class answers { fieldValue + 6 }
every { mock setProperty "property" value any<Int>() } propertyType Int::class answers  { fieldValue += value }
every {
    mock.property = any()
} propertyType Int::class answers {
    fieldValue = value + 1
} andThen {
    fieldValue = value - 1
}

Multiple interfaces

Add extra behavior through interfaces and stub it.

val spy = spyk(System.out, moreInterfaces = Runnable::class)

spy.println(555)

every {
    (spy as Runnable).run()
} answers {
    (self as PrintStream).println("Run! Run! Run!")
}

val thread = Thread(spy as Runnable)
thread.start()
thread.join()

Mocking nothing

There is nothing special here. If you have a function that returns Nothing:

fun quit(status: Int): Nothing {
    exitProcess(status)
}

Then you can, for example, throw an exception as behavior.

every { quit(1) } throws Exception("this is a test")

Matcher extensibility

A very simple way is to attach to MockKMatcherScope or MockKVerificationScope functions and use the match function to create a new matcher.

fun MockKMatcherScope.seqEq(seq: Sequence<String>) = match<Sequence<String>> {
    it.toList() == seq.toList()
}

You can also create advanced matchers by implementing the Matcher interface.

Settings file

To adjust parameters globally, specify some settings in a resource file.

Usage:

  1. Create the resource file io/mockk/settings.properties.
  2. Enter one of the following options.
relaxed=true|false
relaxUnitFun=true|false
recordPrivateCalls=true|false

DSL tables

The following tables help you learn the DSL.

Top level functions

Function Description
mockk<T>(...) Creates a regular mock.
spyk<T>() Builds a spy using the default constructor.
spyk(obj) Builds a spy by copying obj.
slot Creates a capture slot.
every Starts a stubbing block.
coEvery Starts a coroutine stubbing block.
verify Starts a verification block.
coVerify Starts a coroutine verification block.
verifyAll Starts a verification block that includes all calls.
coVerifyAll Starts a verification block that includes all coroutine calls.
verifyOrder Starts a verification block that checks order.
coVerifyOrder Starts a verification block that checks coroutine order.
verifySequence Starts a verification block that checks whether all calls occurred in the specified sequence.
coVerifySequence Starts a verification block that checks whether all coroutine calls occurred in the specified sequence.
excludeRecords Excludes some records from calls.
confirmVerified Confirms that all recorded calls were verified.
clearMocks Clears specified mocks.
registerInstanceFactory Allows redefining how a specific object is instantiated.
mockkClass Creates a regular mock by passing a class as a parameter.
mockkObject Mocks any object, or cancels it if it has already been converted.
unmockkObject Reverts an object mock to a regular object.
mockkStatic Mocks static members in a class, or cancels them if already converted.
unmockkStatic Reverts a static mock to a regular class.
clearStaticMockk Clears static mocks.
mockkConstructor Mocks constructors for a class, or cancels them if already converted.
unmockkConstructor Reverts constructor mocks to a regular class.
clearConstructorMockk Clears constructor mocks.
unmockkAll Unmocks object mocks, static mocks, and constructor mocks.
clearAllMocks Clears regular mocks, object mocks, static mocks, and constructor mocks.

Matchers

By default, simple arguments are matched using eq().

Matcher Description
any() Matches any argument.
allAny() Special matcher that uses any() instead of eq() for simple arguments.
isNull() Checks whether the value is null.
isNull(inverse=true) Checks whether the value is not null.
ofType(type) Checks whether the value belongs to the type.
match { it.startsWith("string") } Matches through the passed predicate.
coMatch { it.startsWith("string") } Matches through the passed coroutine predicate.
matchNullable { it?.startsWith("string") } Matches nullable values through the passed predicate.
coMatchNullable { it?.startsWith("string") } Matches nullable values through the passed coroutine predicate.
eq(value) Matches if the value equals the provided value through deepEquals.
eq(value, inverse=true) Matches if the value does not equal the provided value through deepEquals.
neq(value) Matches if the value does not equal the provided value through deepEquals.
refEq(value) Matches if the value equals the provided value by reference comparison.
refEq(value, inverse=true) Matches if the value does not equal the provided value by reference comparison.
nrefEq(value) Matches if the value does not equal the provided value by reference comparison.
cmpEq(value) Matches if the value equals the provided value through compareTo.
less(value) Matches if the value is less than the specified value through compareTo.
more(value) Matches if the value is greater than the provided value through compareTo.
less(value, andEquals=true) Matches if the value is less than or equal to the specified value through compareTo.
more(value, andEquals=true) Matches if the value is greater than or equal to the specified value through compareTo.
range(from, to, fromInclusive=true, toInclusive=true) Matches if the value is within the range through compareTo.
and(left, right) Logically combines two matchers.
or(left, right) Combines two matchers with logical OR.
not(matcher) Negates a matcher.
capture(slot) Captures a CapturingSlot value.
capture(mutableList) Captures values into a list.
captureNullable(mutableList) Captures values into a list, including null values.
captureLambda() Captures a lambda.
captureCoroutine() Captures a coroutine.
invoke(...) Invokes the matching argument.
coInvoke(...) Invokes the matching coroutine argument.
hint(cls) Indicates the next return type in case it was erased.
anyVararg() Matches all elements of a vararg.
varargAny(matcher) Matches if one element matches the matcher.
varargAll(matcher) Matches if all elements match the matcher.
any...Vararg() Matches all elements of a vararg, by primitive type.
varargAny...(matcher) Matches if one element matches the matcher, by primitive type.
varargAll...(matcher) Matches if all elements match the matcher, by primitive type.

Some special matchers are available only in verification mode.

Matcher Description
withArg { code } Matches any value and allows code execution.
withNullableArg { code } Matches a nullable value and allows code execution.
coWithArg { code } Matches any value and can run coroutine code.
coWithNullableArg { code } Matches a nullable value and can run coroutine code.

Validators

Validator Description
verify { mock.call() } Verifies that the call was executed.
verify(inverse=true) { mock.call() } Verifies that the call was not executed.
verify(atLeast=n) { mock.call() } Verifies that the call was executed at least n times.
verify(atMost=n) { mock.call() } Verifies that the call was executed at most n times.
verify(exactly=n) { mock.call() } Verifies that the call was executed exactly n times.
verifyAll { mock.call1(); mock.call2() } Verifies that only the specified calls were executed on the mentioned mocks.
verifyOrder { mock.call1(); mock.call2() } Verifies that calls happened in the specified order.
verifySequence { mock.call1(); mock.call2() } Verifies that only the specified sequence of calls was performed on the mentioned mocks.
verify { mock wasNot Called } Verifies that the mock was not called.
verify { listOf(mock1, mock2) wasNot Called } Verifies that the list of mocks was not called.

Answers

One or more additional answers can follow an answer.

Helper Description
returns value Specifies that a matching call returns the specified value.
returnsMany list Specifies that matching calls return values from the list, with subsequent calls returning the next elements.
throws ex Specifies that a matching call throws an exception.
answers { code } Specifies that a matching call answers with a code block in answer scope.
coAnswers { code } Specifies that a matching call answers with a coroutine code block in answer scope.
answers answerObj Specifies that a matching call answers with an Answer object.
answers { nothing } Specifies that a matching call answers with null.
just Runs Specifies that a matching call returns Unit, returning null.
propertyType Class Specifies the backing field accessor type.
nullablePropertyType Class Specifies the backing field accessor type as nullable.

Additional answer

Each resulting call returns the next answer, with the last value retained. This is similar to the meaning of returnsMany.

Additional helper Description
andThen value Specifies that a matching call returns one specified value.
andThenMany list Specifies that matching calls return values from the list as each next element is returned.
andThenThrows ex Specifies that a matching call throws an exception.
andThen { code } Specifies that a matching call answers with a code block scoped in answer scope.
coAndThen { code } Specifies that a matching call answers with a coroutine code block scoped in answer scope.
andThenAnswer answerObj Specifies that a matching call answers with an Answer object.
andThen { nothing } Specifies that a matching call answers with null.

Answer scope

Parameter Description
call Call object consisting of invocation and matcher.
invocation Contains information about the actual function called.
matcher Contains information about the matcher used for the call combination.
self Refers to the object that was called.
method Refers to the function that was called.
args Refers to call arguments.
nArgs Number of call arguments.
arg(n) The nth argument.
firstArg() First argument.
secondArg() Second argument.
thirdArg() Third argument.
lastArg() Last argument.
captured() Last element of a list, convenient when capturing to a list.
lambda<...>().invoke() Invokes a captured lambda.
coroutine<...>().coInvoke() Invokes a captured coroutine.
nothing Null value when an answer returns nothing.
fieldValue Accesses the property backing field.
fieldValueAny Accesses the property backing field as Any?.
value Value cast to the same type as the property backing field.
valueAny Value being set as Any?.

Vararg scope

Parameter Description
position Position in the vararg array argument.
nArgs Total number of vararg array arguments.

Source