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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With