doNothing() does not work when i want to mock data and test UI Fragment(当我想模拟数据并测试 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() 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当我想模拟数据并测试 UI 片段时,doNothing() 不起
- Android - 拆分 Drawable 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
