問題描述
我正在嘗試模擬一個方法以查看我是否正確處理了異常.這是據(jù)我所知.
I'm trying to mock a method to see if I handle an exception correctly. This is as far as I get.
界面:
interface SampleManager {
void deleteVariome(String specimenId, String analysisId) throws Exception;
// ...
}
單元測試:
// ...
SampleManger sampleManager = mock(SampleManager.class);
// below is line 753
doThrow(Exception.class).when(sampleManager).deleteVariome(sample1.getId(), analysisId);
結(jié)果:
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at ...server.ArchiveManagerImplUTest.deleteVariomeFails(ArchiveManagerImplUTest.java:753)
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(); <-- this looks a log like what I did!
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer! <-- I have a lot of other mocks of this interface in this test that work.
推薦答案
從我剛剛遇到的一個相同問題中,我懷疑 sample
是一個 mock,并且您將 sample 存根.getId()
其他地方?無論如何,這在我的情況下導(dǎo)致了這個問題.
From an identical issue that I just ran into, I suspect that sample
is a mock, and you stubbed sample.getId()
elsewhere? That caused this problem in my case, anyhow.
由于某種原因,如果您以這種方式傳遞給與 doThrow
一起使用的存根的參數(shù)之一是您也模擬的方法的結(jié)果,那么 Mockito 會感到不安.也許這是一種避免無限循環(huán)的重入檢查,我不知道.
For some reason, Mockito gets upset if one of the arguments you pass to the stub used with doThrow
in this way is the result of a method you also mocked. Perhaps it's a re-entrancy check of sorts to avoid infinite loops, I don't know.
無論如何,嘗試將 sample.getId()
替換為常量值,這應(yīng)該可以解決問題.您可以考慮使用在測試中聲明的常量來進行模擬和任何進一步的使用.然后,您還可以通過添加另一個對 verify
的調(diào)用來檢查您正在測試的方法是否使用了 sample.getId()
.
Regardless, try replacing sample.getId()
with a constant value and that should solve the issue. You could consider using a constant declared in your test for both the mock and any further uses of it. You could then also check that sample.getId()
was used by the method you're testing by adding another call to verify
.
這篇關(guān)于doThrow 中看起來正確的 Mockito 異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!