可以在Kotlin中使用Mockito吗? [英] Is it possible to use Mockito in Kotlin?
本文介绍了可以在Kotlin中使用Mockito吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到的问题是 Matchers.anyObject()
返回 null
。当用于仅接受非可空类型的mock方法时,它会导致抛出不应为null异常。
The problem I'm facing is that Matchers.anyObject()
returns null
. When used to mock method that only accepts non-nullable types it causes a "Should not be null" exception to be thrown.
`when`(mockedBackend.login(anyObject())).thenAnswer { invocationOnMock -> someResponse }
模拟方法:
public open fun login(userCredentials: UserCredentials): Response
推荐答案
有两种可能的解决方法:
There are two possible workarounds:
private fun <T> anyObject(): T {
Mockito.anyObject<T>()
return uninitialized()
}
private fun <T> uninitialized(): T = null as T
@Test
fun myTest() {
`when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}
另一种解决方法是
private fun <T> anyObject(): T {
return Mockito.anyObject<T>()
}
@Test
fun myTest() {
`when`(mockedBackend).login(anyObject())).thenAnswer { ... }
}
这是关于此的更多讨论主题,首先建议解决方法。
Here is some more discussion on this topic, where the workaround is first suggested.
这篇关于可以在Kotlin中使用Mockito吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文