我正在尝试测试ViewModel以确保livedata得到正确的更新。然而,当使用ArgumentMatchers.any()时,它失败了,IllegalStateException说:
ArgumentMatchers.any(mViewModel.CountSubscriber::class.java)不能为空
@Test
fun emitValueIfCountIs7() {
doAnswer { invocation: InvocationOnMock ->
val subscriber: mViewModel.CountSubscriber = invocation.getArgument(0)
subscriber.onNext(7)
null
}.`when`(countUseCase).execute(
ArgumentMatchers.any(mViewModel.CountSubscriber::class.java),
ArgumentMatchers.any(Parameters::class.java)
)
// When
mViewModel.getCount()
// Verify
assert(mViewModel.countResponse.value != null)
}我使用的是Kotlin,它有以下依赖项:
testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-inline:2.23.4"
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.1.0"这是我的进口品:
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.nhaarman.mockitokotlin2.doAnswer
import io.reactivex.Observable
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.mockito.invocation.InvocationOnMock奇怪的是,它以前是起作用的,我不知道发生了什么会影响到这一点。
发布于 2020-05-12 07:59:40
让匹配者和Kotlin一起工作可能是个问题。如果使用kotlin编写的方法不接受可空参数,则不能使用Mockito.any()与其匹配。这是因为它可以返回void,并且不能分配给非空参数。
如果匹配的方法是用Java编写的,那么我认为它将工作,因为所有Java对象都是隐式可空的。
一个可能的解决方案是使用像莫奇托-科特林这样的库,但是您可以通过自己编写几行代码轻松地解决这个问题。
如果您需要输入任何类型(类型:类)
private fun <T> any(type: Class<T>): T = Mockito.any<T>(type)或
您可以使用这个匹配器而不是Matchers.any():
object MockitoHelper {
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
@Suppress("UNCHECKED_CAST")
fun <T> uninitialized(): T = null as T
}在kotlin测试中使用MockitoHelper.anyObject()而不是any()。
您可以在以下文章中找到更多信息:与Kotlin一起使用Mockito
本文中讨论了可能的解决方案:在科特林能用莫基托吗?
发布于 2020-08-11 01:33:28
@Ana在问题的评论部分提到了正确的解决方案。是的,如果你使用的是Koltin + mockitoKotlin。确保您使用的是以下导入:
1 -使用Mockito-kotlin:
来自莫奇托-科特林的import org.mockito.kotlin.any而不是import org.mockito.Mockito.any
testImplementation "org.mockito.kotlin:mockito-kotlin:$mockito_kotlin_version"2 -或者如果您使用的是早一些的mockito kotlin版本,原版由nhaarman在之前创建。
import com.nhaarman.mockitokotlin2.any来自nhaaram's Mockito-kotlin而不是import org.mockito.Mockito.any
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:$mockito_kotlin2_version"顺便说一句,如果你使用的是Android或IntelliJ的想法。默认情况下,mockitokotlin库中的any()应该是italic。
请注意行尾的any()。这是来自mockitokotlin的

这是any()从mockito

感谢@Sattar推荐的编辑。
发布于 2022-01-07 00:15:44
莫奇托-科特林增加了对带有anyOrNull()的可空args的支持
`when`(myMock.doesThis(any(), anyOrNull())).thenReturn(someObject)https://stackoverflow.com/questions/59230041
复制相似问题