在Mockito中,我可以创建一个类的模拟,并为该模拟函数调用指定默认答案,如下所示:
  whenever(this.strings).thenReturn(mock(StringProvider::class.java, StringProviderAnswer()))答案可能是
    class StringProviderAnswer : Answer<Any?> {
    private val delegate = Mockito.RETURNS_DEFAULTS!!
    override fun answer(invocation: InvocationOnMock?): Any? {
        val invocationMethodReturn = invocation?.method?.returnType
        val stringType = String::class.java
        return when (invocationMethodReturn) {
            stringType -> invocation.method?.name.toString() + invocation.arguments.joinToString()
            else -> delegate.answer(invocation)
        }
    }
}所以我可以用一种非常详细的方式把一个类的所有功能拼出来。有办法对付莫克吗?我看到有一个Answer类,但是我没有看到一种明显的方法来创建一个模拟,除了这作为默认的答案策略。
发布于 2022-07-08 20:23:51
如果我正确理解,您需要一个当返回类型为String时返回方法名称和参数的模拟,而另一个是默认值。
您的when语句的第二个分支可以通过轻松的模拟轻松地实现,即用mockk(YourClass::class, relaxed = true)来模拟类,或者用@RelaxedMockK而不是@MockK注释模拟。
至于第一个分支,mockk目前不支持使用返回类型的所有方法:我认为实现这种行为的唯一方法是执行以下操作:
every { 
    yourMock.method(any())
} answers { 
    method.name + args.joinToString(" ") 
}对于您模拟的类中的每个方法。
在mockk函数中添加一个参数来定义覆盖DefaultAnswerer的策略应该不会太困难,我很乐意回顾一下关于它的PR。
https://stackoverflow.com/questions/72905380
复制相似问题