mockkStatic for extension method with generic parameter: "Not enough information to infer type variable T"

Viewed 137

FYI: I'm currently using Mockk-1.12.4 and Kotlin-1.6

I've got an extension method that returns an object of type T:

fun <T> Entity.selectReferenceAsSingleObject(referenceName: String): T {
    return this.selectReferencesByName(referenceName).single().asObjet() as T
}

This is defined as top level function in an Extentions.kt file (so not a class). I'm wanting to mock this with MockK by using mockkStatic

mockkStatic(Entity::selectReferenceAsOptionalSingleObject)

However I'm getting the error:

Not enough information to infer type variable T

because it cannot work out what type I should be mocking. I've tried adding my type parameter in a bunch of places

mockkStatic<KFunction<MyType>>(Entity::selectReferenceAsSingleObject)
mockkStatic<MyType>(Entity::selectReferenceAsSingleObject)
mockkStatic(Entity<KFunction<MyType>>::selectReferenceAsSingleObject)
mockkStatic(Entity<MyType>::selectReferenceAsSingleObject)
mockkStatic(Entity::<KFunction<MyType>>selectReferenceAsSingleObject)
mockkStatic(Entity::<MyType>selectReferenceAsSingleObject)
mockkStatic(Entity::selectReferenceAsSingleObject<KFunction<MyType>>)
mockkStatic(Entity::selectReferenceAsSingleObject<MyType>)
mockkStatic(Entity::selectReferenceAsSingleObject as KFunction<MyType>)
mockkStatic(Entity::selectReferenceAsSingleObject as MyType)

But nothing works and it either tells me the same error or tells me that type arguments are not allowed there. I'm not sure what I need to do to fix my syntax as IntelliJ isn't giving me any hints so I feel kind of stuck. Any help would be appreciated.

1 Answers

Try this:

mockkStatic("your.package.YourFileExtensionKt")

you can also give the file a nice name:

@file:JvmName("Extension")

would look like this:

mockkStatic("your.package.Extension")

anyway for the test to work you must use a mock in the extended class, in this case Entity, it would look like this:

@Test
fun test() {
    val entity : Entity = mockk(relaxed = true)
    every { entity.selectReferenceAsSingleObject<Any>(any()) } returns "whatever"

    val result = entity.selectReferenceAsSingleObject<Any>("test")

    assertEquals("whatever", result)
}
Related