develop with

How to use Mockk in Testing

Using mockk to make testing easier

Mockk is a library that you can use for mocking objects in Kotlin tests. It is a vary clean library and it makes using mocks so much easier when you are building out complex applications in Kotlin.

Get library

Resolve the dependency through maven by defining it in your pom.xml.

<dependency>
    <groupId>io.mockk</groupId>
    <artifactId>mockk</artifactId>
    <version>1.9.3</version>
    <scope>test</scope>
</dependency>

or load via gradle:

testCompile group: 'io.mockk', name: 'mockk', version: '1.9.3'

Library usage

First, start with a simple mock of a method on a class that you want to return with something else. This is the easiest way to get started with Mockk. The basic approach would be to create the mock object with the given class as the type, then define the methods you want to answer too.

Start with importing lib:

import io.mockk.*

For Example, let’s mockk a made up object:

val objResult = mockk<ObjectResult>()
// every call to eTag method, respond with timestamp string
every {
    objResult.eTag
} returns Instant.now().toString()

To make your mock objects more powerful, Mockk provides a way to capture parameters you can use later in a method response. You define a slot that will be used to capture into, and then in the answers block you can respond or set something for the given slot.

For example:

// For a given class / object like this
class MyObject{
   fun world(hello:String) :World {
      val world = World()
      return world
   }
}

// Mock with the following
val helloSlot = slot<String>()
val myObj = mockk<MyObject>()
every {
  myObj.world(capture(helloSlot))  
} answers {
  // get the value from the slot that was captured
    val myWorld = World(helloSlot.captured)
    return myWorld
}  

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.