Java 间谍莫基托与合作计划
我有一个名为ViewModel的类 当变量Java 间谍莫基托与合作计划,java,android,unit-testing,kotlin,kotlin-coroutines,Java,Android,Unit Testing,Kotlin,Kotlin Coroutines,我有一个名为ViewModel的类 当变量shouldCheck更改时,调用函数open class ViewModel { val shouldCheck = MutableLiveData<Boolean>() val check by lazy { shouldCheck.switchMap { liveData(Dispatchers.IO) { open()
shouldCheck
更改时,调用函数open
class ViewModel {
val shouldCheck = MutableLiveData<Boolean>()
val check by lazy {
shouldCheck.switchMap {
liveData(Dispatchers.IO) {
open()
emit(true)
}
}
}
fun open(){
println("I am open")
}
}
在调试模式下,我检查并调用了函数open。然后打印“我是打开的”,但我有这个错误
Wanted but not invoked:
viewModel.open();
However, there were exactly 2 interactions with this mock:
如果我删除switchMap和liveData(Dispatchers.IO)
测试通过。
但我需要它。根据谷歌的说法:
我的建议是如下注入调度程序:
class MyViewModel(private val ioDispatcher: CoroutineDispatcher)
并在测试中使用
TestCoroutineDispatcher
,这可能会有所帮助您是否在模拟ViewModel
对吗?这个设置看起来怎么样?@NagyRobi我编辑了这个问题,我通过spy设置了ViewModel,你现在可以看到,open()
是MyIdentificationPayViewModel()的函数
还是一些内部函数?是的,ViewModel中的open()函数,我更改了代码。我认为这个问题来自于switchMap或coroutines@NagyRobi我再次更新代码使用此类协程结构如果我正确,只有您的主调度程序将被替换为TestCoroutineDispatcher
,open仍将在IO
上运行我知道此错误与switchMap有关。你能看到这个帖子吗
class MyViewModel(private val ioDispatcher: CoroutineDispatcher)