本文介绍了当我想模拟数据并测试 UI 片段时,doNothing() 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我要用 Espresso test fragment 然后我想 mock viewmodels代码> 和成员.
I am going to test fragment with Espresso then i want to mock viewmodels and members.
在我的 viewModel 我有一个 void function 像这样:
In my viewModel i have a void function like this :
fun getLoginConfig() {
viewModelScope.launchApiWith(_loginConfigLiveData) {
repository.getLoginConfig()
}
}
在测试 fragment 当我们从 viewModel 调用 getLoginConfig() 我想用 mock>doNothing() 但我面临这个错误:
In test fragment when we call getLoginConfig() from viewModel i want to mock it with doNothing() but i faced with this error :
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, which is not supported
3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
在 testFragmentClass 的这一行:
@Before
fun setUp() {
//logOut
mockVm = mock(SplashVM::class.java)
loadKoinModules(module {
single {
mockVm
}
})
}
doNothing().`when`(mockVm.getLoginConfig()).let {
mockVm.loginConfigLiveData.postValue(Resource.Success(
LoginConfigResponse(
listOf("1"),1,1,"1",true)
))
}
推荐答案
一些事情:
doNothing什么都不做,这对于 mock 上的 void 方法来说是不必要的.这是默认行为.您只希望doNothing用于间谍或已存根的模拟.- 如果您希望在响应模拟调用时发生特定的事情,
doAnswer就是这样去. - 在
doVerb语法中,Mockito 期望那里只有一个变量;表达式不应调用 mock 上的方法,否则 Mockito 会认为您已经失去兴趣并抛出 UnfinishedStubbingException.
doNothingjust does nothing, which is unnecessary for void methods on a mock. It's the default behavior. You only wantdoNothingfor spies or already-stubbed mocks.- If you want something specific to happen in response to a call on a mock,
doAnsweris the way to go. - In
doVerbsyntax, Mockito expects that there is only a variable there; the expression should not call a method on a mock, or else Mockito thinks you've lost interest and throws UnfinishedStubbingException.
因此你的修复看起来像:
Therefore your fix looks like:
doAnswer {
mockVm.loginConfigLiveData.postValue(Resource.Success(
LoginConfigResponse(
listOf("1"),1,1,"1",true)
))
}.`when`(mockVm).getLoginConfig()
这篇关于当我想模拟数据并测试 UI 片段时,doNothing() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)