本文介紹了當我想模擬數據并測試 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.
doNothing
just does nothing, which is unnecessary for void methods on a mock. It's the default behavior. You only wantdoNothing
for spies or already-stubbed mocks.- If you want something specific to happen in response to a call on a mock,
doAnswer
is the way to go. - In
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模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!