Mocking library for Kotlin

Argument Matchers

Verify

verify(atLeast = 5, atMost = 7) { 
  mock1.call(5)
}
 
verifyAll { 
  mock1.call(5)
}
 
verifySequence {
  mock1.call(1)
  mock1.call(2)
  mock1.call(3)
}
 
verifyOrder {
  mock1.call(1)
  mock1.call(3)
}

Captured Argument

every { 
  mock.divide(capture(slot), any()) 
} answers {
  slot.captured * 11
}
mock.divide(5, 2) // returns 55.

Mock

val mock = mockk<Divider>(relaxed = true)
 
mock.divide(5, 2) // returns 0

Spy

Spies give the possibility to set expected behavior and do behavior verification while still executing original methods of an object.

class Adder {
    fun magnify(a: Int) = a
    fun add(a: Int, b: Int) = a + magnify(b)
}
 
val spy = spyk(Adder())
every { spy.magnify(any()) } answers { firstArg<Int>() * 2 }