Is there a recommended / suggested way of writing ...
# multiplatform
j
Is there a recommended / suggested way of writing mockable types? It seems that it’s easier to mock Kotlin code that makes use of interfaces, like with Mockitive. But writing an interface first is not the most obvious way to write code. It also makes it difficult to know how best to construct abstracted types. Do you use a factory object? Extension functions on the interface? Something else?
a
the Kotlin style guide has an example under ‘Factory functions’ https://kotlinlang.org/docs/coding-conventions.html#function-names
Copy code
interface Foo { /*...*/ }

class FooImpl : Foo { /*...*/ }

fun Foo(): Foo { return FooImpl() }
This approach is used by KxS, where
JsonPrimitive
is a public sealed class with lots of
JsonPrimitive()
factory functions, while the implementation
JsonLiteral
is an internal class type https://github.com/Kotlin/kotlinx.serialization/blob/9056f309cab0e3f361547c48fdc8f0904443f8ab/formats/json/commonMain/src/kotlinx/serialization/json/JsonElement.kt#L52-L56
j
Fantastic. Thank you!
d
Actually writing interfaces for every class is a pretty common thing in projects using clean architecture to make your code decoupled and easier to test. Also considering that with mockmp (mocking framework for kmp) you can only mock interfaces, it definitely makes sense to do so.
j
I totally agree, Daniel. I am running into issues with multiplatform libraries that I want to depend on and having a hard time writing code that lets me mock them. (For example, see my recent pull request for KVault.) One of the other issues I’ve run into is that interfaces don’t include companion objects as part of the contract. This makes it harder to express some things like I would expect. But, I realize that companion objects are supposed to be different from static methods.