我要用 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.doNothing
just does nothing, which is unnecessary for void methods on a mock. It's the default behavior. You only want doNothing
for spies or already-stubbed mocks.doAnswer
is the way to go.doVerb
syntax, 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() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!