Kotlin:手动内联通用函数会产生不同的结果吗? [英] Kotlin: Manually inlining a generic function produce a different result?
问题描述
我有一个简单的测试班
class SimpleClassTest {
private fun <T> 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())
}
}
它可以正常运行并通过.
It works fine and pass.
由于私有通用anyObject()
函数仅使用一次,因此我决定对其进行内联(手动),即不再需要该函数,因此我可以从中更改
Since the private generic anyObject()
function is only used once, so I decide to inlining it (manually) i.e. remove the need of that function, whereby I change from
verify(injectedObject).settingDependentObject(anyObject())
到
verify(injectedObject).settingDependentObject(Mockito.anyObject<DependentClass>())
但是现在这个错误为
java.lang.IllegalStateException: Mockito.anyObject<DependentClass>() must not be null
However this now error as
java.lang.IllegalStateException: Mockito.anyObject<DependentClass>() must not be null
我在将函数调用内联到直接语句时做错了什么
Anything I did wrong inlining the function call to a direct statement?
使用之间有什么区别
private fun <T> anyObject(): T {
return Mockito.anyObject<T>()
}
及以下?
Mockito.anyObject<DependentClass>()
推荐答案
Mockito.anyObject()
的来源:
/**
* Matches anything, including null.
* <p>
* This is an alias of: {@link #any()} and {@link #any(java.lang.Class)}
* <p>
* See examples in javadoc for {@link Matchers} class
*
* @return <code>null</code>.
*/
public static <T> T anyObject() {
return (T) reportMatcher(Any.ANY).returnNull();
}
此方法为Mockito设置一些内部状态,然后继续返回null
.由于您期望在settingDependentObject()
方法中使用非空实例,因此运行时将失败.
This method sets some internal state for Mockito, and then proceeds to return null
. Since you're expecting a non-null instance in your settingDependentObject()
method, the runtime fails.
为什么您的第一种方法成功了,但是我不确定.将null
投射到T
似乎可以,但对我而言不再有效.因此,我也无法使您的第一个实现成功.
Why your first method succeeded, however, I'm not sure. Casting null
to T
seemed to work a while ago, but it doesn't work for me anymore. For that matter, I can't get your first implementation to succeed either.
这篇关于Kotlin:手动内联通用函数会产生不同的结果吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!