在 'every' 块中指定方法参数 class 类型

Specify method paramater class type in 'every' block

我在 save() 方法(Spring 框架)中使用 any() 语句时遇到问题。我收到错误:

Type inference failed: Not enough information to infer parameter T in inline fun any( ): T
Please specify it explicitly.

有什么方法可以传递方法参数,这样我就不会出现错误了吗?我试图将对象作为参数传递,但 save() 方法创建了一个需要使用 any() 的新对象。

every { repository.save(any()) } returns classObject

传递对象时出错:

io.mockk.MockKException: no answer found for: Repository(#10).save(app.core.model.Class@734a4045)

您可以通过 any<Type>().

为函数指定类型参数

示例:

fun <T> any(defaultValue: T? = null): T? = defaultValue


fun main() {
    val s = any<String>()
    println(s)
    val i = any<Int>()
    println(i)
    val j = any(10) // type inferred from arg
    println(j)
    val k: Int? = any() // type inferred from variable
    println(k)
}

打印:

null
null
10
null

无法推断类型的原因是,在您的情况下,save() 可能接受类型 Any 的值,因此编译器无法推断任何特定类型。

顺便说一句,如果您需要在泛型函数中访问 T,Kotlin 允许您创建 function reified.