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

jmfayard

03/10/2022, 12:37 PM
Hello, I have a.
sealed class Either
which either a
Left
or a
Right
But actually no, because in my unit tests, mockk creates a subclass of
Either
which is neither Left nor Right and break the contract of my type Is there a way to forbit mockkk to create a subclass of a sealed class?
e

eurycea

03/10/2022, 12:44 PM
Do you need to mock an
Either
or are you wanting a warning/error when you try to mock a sealed class?
j

jmfayard

03/10/2022, 12:52 PM
I want Koin to crash
e

ephemient

03/10/2022, 12:53 PM
currently no
in the near future https://youtrack.jetbrains.com/issue/KT-41214 will enable JVM support for sealed classes to prevent unauthorized subclasses even through reflective means
👍 2
j

jmfayard

03/10/2022, 1:17 PM
Thanks, I +1ed the issue Wouldn't it be possible in the meantime to add to the sealed class an interface or an annotation like
@ForbidMockk
to tell explicitely that the class is not to be mocked?
I've found an acceptable solution
Copy code
JvmMockKGateway.anyValueGeneratorFactory = { voidInstance ->
    object : JvmAnyValueGenerator(voidInstance) {
        override fun anyValue(cls: KClass<*>, isNullable: Boolean, orInstantiateVia: () -> Any?): Any? {
            if (cls == Either::class) return Either.Left(MockingError)
            return super.anyValue(cls, isNullable, orInstantiateVia)
        }
    }
}
45 Views