How to mock a Kotlin singleton object?

user3284037 picture user3284037 · Jun 22, 2016 · Viewed 21.8k times · Source

Given a Kotlin singleton object and a fun that call it's method

object SomeObject {
   fun someFun() {}
}

fun callerFun() {
   SomeObject.someFun()
}

Is there a way to mock call to SomeObject.someFun()?

Answer

LeoColman picture LeoColman · Jan 22, 2018

There's a very nice mocking library for Kotlin - Mockk, which allows you to mock objects, the exact same way you're desiring.

As of its documentation:


Objects can be transformed to mocks following way:

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

mockkObject(MockObj) // aplies mocking to an Object

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

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

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

To revert back use unmockkAll or unmockkObject:

@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 limits you can create new instances of objects if testing logic needs that:

val newObjectMock = mockk<MockObj>()