Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Multiplatform: How to mock objects in a unit test for iOS

I'm working on a Kotlin-multiplatform (KMP) library for iOS / Android. I have written some unit tests for JVM, for which I use MockK to create spies and mocks, but MockK doesn't support Kotlin native fully yet.

Therefore, I was wondering how others working on KMP projects write unit tests for the iOS platform. An example would be really appreciated.

like image 361
Abel Avatar asked Oct 10 '19 10:10

Abel


1 Answers

You can use Mockative to mock interfaces in Kotlin/Native and Kotlin Multiplatform, not unlike how you'd mock dependencies using MockK or Mockito.

Full disclosure: I am one of the authors of Mockative

Here's an example:

class GitHubServiceTests {
    @Mock val api = mock(classOf<GitHubAPI>())

    val service = GitHubService(api)

    @Test
    fun test() {
        // Given
        val id = "mockative/mockative"
        val mockative = Repository(id = id, name = "Mockative")
        given(api).invocation { fetchRepository(id) }
            .thenReturn(mockative)

        // When
        val repository = service.getRepository(id)

        // Then
        assertEquals(mockative, repository)

        // You can also verify function calls on mocks
        verify(api).invocation { fetchRepository(id) }
            .wasInvoked(exactly = once)
    }
}

Spies aren't currently supported, but they are on the roadmap.

like image 109
Nicklas Jensen Avatar answered Sep 23 '22 10:09

Nicklas Jensen