kotlin 具有泛型参数的扩展方法的mockkStatic:“信息不足,无法推断类型变量T”

k7fdbhmy  于 2023-03-19  发布在  Kotlin
关注(0)|答案(2)|浏览(231)

仅供参考:我目前使用的是Mockk-1.12.4和Kotlin-1.6
我有一个扩展方法,它返回一个类型为T的对象:

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

这在Extensions.kt文件中被定义为顶级函数(所以不是类)。我想使用mockStatic在MockK中模拟它

mockkStatic(Entity::selectReferenceAsOptionalSingleObject)

但是我得到错误:

Not enough information to infer type variable T

因为它无法计算出我应该模拟什么类型。我试过在很多地方添加类型参数

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)

但是没有任何效果,它要么告诉我同样的错误,要么告诉我类型参数是不允许的。我不知道我需要做什么来修复我的语法,因为IntelliJ没有给我任何提示,所以我觉得有点卡住了。任何帮助将不胜感激。

mitkmikd

mitkmikd1#

试试这个:

mockkStatic("your.package.YourFileExtensionKt")

你也可以给予文件一个好名字:

@file:JvmName("Extension")

会是这样的

mockkStatic("your.package.Extension")

无论如何,为了让测试工作,你必须在扩展类中使用一个mock,在这个例子中是Entity,它看起来像这样:

@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)
}
bihw5rsg

bihw5rsg2#

必须注意以下几点:
如果您的Kotlin文件是.package.yourFileExtension.kt,那么mockkStatic应该如下所示:

mockkStatic("your.package.YourFileExtensionKt")

Kt由Kotlin编译器自动添加为后缀

相关问题