我在下面有一个使用内联乐趣的通过测试。
class SimpleClassTest {
private inline fun <reified T: Any> anyObject(): T {
return Mockito.anyObject<T>()
}
lateinit var simpleObject: SimpleClass
@Mock lateinit var injectedObject: InjectedClass
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
}
@Test
fun testSimpleFunction() {
simpleObject = SimpleClass(injectedObject)
simpleObject.simpleFunction()
verify(injectedObject).settingDependentObject(anyObject())
}
}
但是现在我想删除内联乐趣,因为它只有一种用法。所以我用实际的类名替换T,即Response(来自Okhttp),并将其直接设置为settingDependentObject
class SimpleClassTest {
lateinit var simpleObject: SimpleClass
@Mock lateinit var injectedObject: InjectedClass
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
}
@Test
fun testSimpleFunction() {
simpleObject = SimpleClass(injectedObject)
simpleObject.simpleFunction()
verify(injectedObject).settingDependentObject(Mockito.anyObject<Response>())
}
}
会失败
java.lang.IllegalStateException: Mockito.anyObject<Response>() must not be null
我如何正确地手动内联并且行为与我private inline fun <reified T: Any> anyObject(): T
时的行为相同?
更新 注意:这是Kotlin: Manually inlining a generic function produce a different result?的后续问题。前面提供了原因,但我无法理解如何正确地内联它。