I use mockito-kotlin, which is super great to do this kind of code, with myMethod
being a suspend function:
mock(MyClass) {
onBlocking { myMethod() }.doReturn("hi")
}
Now I'd like to use a context receiver in myMethod, like
context(MyContext)
suspend fun myMethod() {
...
}
The mock definition now doesn't compiler anymore because it expects a context, so I could do:
mock(MyClass) {
onBlocking {
with(MyContext) {
myMethod()
}
}.doReturn("hi")
}
which works fine, but I have the same piece of code at 50 places, so I'd like to define a helper method that provided the context automatically. The best I could achieve is (this is mostly a copy-paste of the original onBlocking
method):
fun <T : Any, R> KStubbing<T>.onBlockingContext(
m: suspend context(MyContext) T.() -> R
): OngoingStubbing<R> {
val context = any<MyContext>()
return runBlocking {
with(context) {
Mockito.`when`(m([email protected]))
}
}
}
However at runtime I have the following error:
java.lang.ClassCastException: class MyClass cannot be cast to class MyContext (MyClass and MyContext are in unnamed module of loader 'app')
Any idea how I could make it work - or another way to put the code in common?