Skip to content

Instantly share code, notes, and snippets.

@motorro
Created January 24, 2023 14:31
Show Gist options
  • Save motorro/66348d27f93f1f54c4689f77ba07555b to your computer and use it in GitHub Desktop.
Save motorro/66348d27f93f1f54c4689f77ba07555b to your computer and use it in GitHub Desktop.
Context receiver mocking with mock
package com.myexample
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Test
import kotlin.test.assertEquals
interface CallContext
class MyClass {
context(CallContext)
fun myMethod(a: Int): Int = a
}
class ContextMockTest {
private val myClassMock: MyClass = mockk()
@Test
fun mockContextWorks() {
every {
with(any<CallContext>()) {
myClassMock.myMethod(any())
}
} returns 123
val context = object : CallContext { }
with(context) {
assertEquals(123, myClassMock.myMethod(1))
}
verify {
with(any<CallContext>()) {
myClassMock.myMethod(1)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment