https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
j

Jilles van Gurp

03/26/2021, 1:08 PM
What are good options for mocking multiplatform kotlin currently? I'm particularly interested in kotlin-js currently but might also need kotlin-native (and of course jvm; we use mockk for that).
b

Big Chungus

03/26/2021, 1:10 PM
Mockk has some rudimentary support for js mocking, but not native. If you want to mock in common, my advice would be to not mock at all, but stub instead. That way you won't need any mock library nor reflection
It's a bit more maintenance, though, since you now have everything you plan on stubbing exposed via interfaces and not classes directly.
j

Joost Klitsie

03/26/2021, 1:37 PM
From Google they now have guidelines to not use mocks and in terms of multiplatform it does make sense to me to not mock, as you will not have to find a multiplatform mocking library. Using interfaces and provide fake implementations should be good enough but to be fair I have to get a bit familiar of the whole concept, as I am/was a big fan of Mockito and Mockk.
b

Big Chungus

03/26/2021, 2:03 PM
The concept is quite simple. Never pass around classes, alway use interfaces.
Copy code
// src/main/kotlin
interface ImportantObject {
  fun check(): Boolean
}

class ImportantObjectImpl: ImportantObject {
  private val actualImplementationReturn: Boolean = true

  override fun check(): Boolean = actualImplementationReturn
}

class Processor {
  fun process(importantObject: ImportantObject): Boolean {
    return importantObject.check()
  }
}

fun main() {
  Processor().process(ImportantObjectImpl()) // returns true
}
And in tests you can then do
Copy code
// src/test/kotlin

class ImportantObjectTest {
  @Test
  fun test() {
    Processor().process(object: ImportantObject {
      override fun check(): Boolean = false
    }) // returns false
  }
}
It's basically more verbose and explicit mocking without reflection
j

Jilles van Gurp

03/29/2021, 8:53 PM
right, I was hoping for something a bit less tedious/primitive. Maybe some kind of compiler plugin or code generation could long term provide an alternative.
b

Big Chungus

03/29/2021, 8:59 PM
In any case, if you need it to work on mpp, you must forget reflection.
j

Jilles van Gurp

03/30/2021, 7:40 AM
I'm OK with generated code via the JVM that mocks. A bit like kotlinx serialization works at compile time. That would allow some reflection magic to happen at compile time. But I guess it's too early for mature test tooling.
b

Big Chungus

03/30/2021, 7:53 AM
I'm waiting until ksp is finally mpp so that i could start writing such plugins for common code. Once that's in, possibilities are endless.
Which is unfortunately blocked by https://github.com/JetBrains/kotlin/pull/4229
Oh wait, it just got merged!
🎉 1
3 Views