我要用 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() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
EditText:禁用文本选择处理程序单击事件上的粘贴EditText: Disable Paste/Replace menu pop-up on Text Selection Handler click event(EditText:禁用文本选择处理程序单击事件上的粘贴/替换菜
2.3 上带有完成 SoftInput 操作标签的多行 EditTextMultiline EditText with Done SoftInput Action Label on 2.3(2.3 上带有完成 SoftInput 操作标签的多行 EditText)
如何在 Android 中检测向左或向右滑动?How to detect the swipe left or Right in Android?(如何在 Android 中检测向左或向右滑动?)
防止在Android中的屏幕旋转对话框解除Prevent dialog dismissal on screen rotation in Android(防止在Android中的屏幕旋转对话框解除)
如何处理 ImeOptions 的完成按钮点击?How do I handle ImeOptions#39; done button click?(如何处理 ImeOptions 的完成按钮点击?)
您如何将 EditText 设置为仅接受 Android 中的数值How do you set EditText to only accept numeric values in Android?(您如何将 EditText 设置为仅接受 Android 中的数值?)