Say I have a Java class Metrics. I defined some extension functions on Metrics in Kotlin
fun Merics.expose(name: String, value: Number) {
// do something
}
Note that the Java class Metrics
also has a method called expose
but with different signature.
I created a test where I mocked a metrics
objects and call a code path where the extension function expose
should be called. But how can I verify that those extension functions are invoked?
I tried to use mockk and mockito-kotlin, none of them seem to know that metrics
object has a new function called expose
with different signatures.
You can not verify that the extension function is called on your mock, as it is not part of that class. The extension function is just a top-level function with a receiver (in your case an instance of Metrics
).
But you can still verify that the extension function was called in your code
You can do this using mockkStatic.
You are passing the the path of the (generated) extension function. Let's assume you created your Metrics
extension function in package org.com
. The extension class should get generated in: com.org.MericsExtensionKt
.
A test that wants to verify the call to your extension function could look like:
@Test
fun check_metrics_expose_extension_was_called() {
mockkStatic("com.org.MericsExtensionKt")
// call your function that is calling Metrics.expose()
// classUnderTest.someFunction()
// this verifies a call to the extension function and their parameters
verify { any<Metrics>().expose(name = any(), value = any()) }
}