mockito 在Activity中模拟注入的私有变量

6yoyoihd  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(167)
class CustomActivity : BaseActivity() {

@Inject
lateinit var viewModelFactory: ViewModelProviderFactory

private val mViewModel: SplashViewModel by viewModels {
    viewModelFactory
}

override fun onResume() {
    super.onResume()
    observeOrderResponse()
}

private fun observeOrderResponse() {
    mViewModel.userObserver.observe(this) { userResponse ->
        updateUIBasedOnUserResponse(userResponse)
    }
}

}
在这段代码中,我想用特定的UserResponse来模拟userObserver(LiveData<UserResponse>)。我如何模拟注入我的视图模型的观察者?
我不能使用AppComponentFactory,因为我的最小sdk值是26。

zvokhttg

zvokhttg1#

val viewModel : SplashViewModel = mockk()
// or you need to Mock Your ViewModelFactory
@Test
fun myTest(){
   val fakeObserver = MutableLiveData<UserResponse>()
   every {viewModel.userObserver } returns fakeObserver
   fakeObserver.value = // put you data that you want to observe
}

相关问题