Testing Kotlin Objects

Monika Kumar Jethani
2 min readMay 22, 2021

--

Let’s start by taking the following Kotlin Object,

object ObjectUnderTest {
fun doSomething(testParameter: String): String {
// do some operation
return "Operation done with $testParameter"
}
}

Now let’s start writing unit test for the above ObjectUnderTest and its method doSomething()

Unit Testing using Mockito
Since Mockito doesn’t support mocking some Kotlin constructs, so we cannot test object. However, it supports testing the interface, so we can have our object extend the interface, that way we end up testing the object.

For instance, we create the following interface,

interface SampleInterface {
fun doSomething(testParameter: String): String
}

and make our Kotlin object extend this interface,

object ObjectUnderTest :  SampleInterface {
fun doSomething(testParameter: String): String {
// do some operation
return "Operation done with $testParameter"
}
}

Now, we can test the interface by mocking it and checking the expected value with the actual value returned,

@Test 
fun testObjectWithMockito() {

val mock = mock<SampleInterface>()
when (mock.doSomething("parameter")).thenReturn("Mocked result")

val answer = mock.doSomething("parameter")
assertEquals("Mocked result", answer)
}

Unit Testing using MockK

MockK is made for Kotlin and supports testing of Kotlin objects, so we can mock object using,

mockkObject(ObjectUnderTest)

Following code unit tests the method of the object for mocked and non-mocked results.

@Test
fun testObjectWithMockK() {

mockkObject(ObjectUnderTest)

// when calling not mocked method
val firstResult = doSomething("param")
// then return real response
assertEquals("Operation done with param", firstResult)

every { doSomething(any()) } returns "Mocked result”

// when calling mocked method
val secondResult = doSomething("param")
// then return mocked response
assertEquals("Mocked result", secondResult)
}

--

--