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

放肆的年华 提交于 2021-01-26 04:53:16

问题


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.


回答1:


Currently, MockK does not support Kotlin/Native or Kotlin/JS. However, both are placed as important items on the project backlog:

  • Kotlin/Native
  • Kotlin/JS

This is a big challenge given that a mocking library relies heavily on language features such as reflection which are not fully supported yet on Kotlin multiplatform (and possibly even can't be supported without considerable workarounds for specific platforms).

This does not prevent you from writing custom mock classes and verify states you set therein, of course, of which the tests will be able to run on all platforms.




回答2:


I looked around and asked in Kotlin' General slack which by the way is a great space where you can ask directly the Kotlin devs and the enthusiasts Kotlin language related questions including multi-platform stuff.

But as for the time I'm writing this, I Don't think you can mock for the common module with Mockk or any other mocking library.

What you can for tests in the common module which is targeted to native as one of the platforms is the old-fashioned interface/impl/stub approach.




回答3:


I test the common sources in androidTest. There Mockk is available.

I think it is sufficient because Android uses exactly the same code as the common module.

shared
> src
>> androidMain 
>> androidTest < tests here
>> commonMain < code here


来源:https://stackoverflow.com/questions/58320492/kotlin-multiplatform-how-to-mock-objects-in-a-unit-test-for-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!