How to mock a method with context receiver? Here's my setup:
interface AProvider {
context(ContextProvider)
fun getA(a: String) = a
}
class ContextProvider
inline fun <reified T : Any> mockkWithContext(noinline block: context(ContextProvider) T.() -> Unit) =
withContext { mockk<T> { block(this@withContext, this@mockk) } }
fun <T> withContext(block: ContextProvider.() -> T) = ContextProvider().block()
class ContextReceiversTest {
@Test
fun `a test`() {
val aProviderMock: AProvider = mockkWithContext {
every { getA(any()) } answers { firstArg() }
}
println(withContext { aProviderMock.getA("a") })
}
}
As you can see the getA method has
ContextProvider
as a receiver. In order to mock it in the test I have to wrap standard
mockk
in
withContext
which provides the required receiver for
getA
. If I run the test, though, it fails on
io.mockk.MockKException: no answer found for: AProvider(#1).getA(com.example.playground.ContextProvider@38b5f25, a)
Apparently mockk expects the receiver as the first argument but obviously I cannot write
every { getA(any(), any()) }
. So my question is how can I mock the method in my case?