問(wèn)題描述
我正在嘗試模擬一個(gè)方法以查看我是否正確處理了異常.這是據(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;
// ...
}
單元測(cè)試:
// ...
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.
推薦答案
從我剛剛遇到的一個(gè)相同問(wèn)題中,我懷疑 sample
是一個(gè) mock,并且您將 sample 存根.getId()
其他地方?無(wú)論如何,這在我的情況下導(dǎo)致了這個(gè)問(wèn)題.
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ì)感到不安.也許這是一種避免無(wú)限循環(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.
無(wú)論如何,嘗試將 sample.getId()
替換為常量值,這應(yīng)該可以解決問(wèn)題.您可以考慮使用在測(cè)試中聲明的常量來(lái)進(jìn)行模擬和任何進(jìn)一步的使用.然后,您還可以通過(guò)添加另一個(gè)對(duì) verify
的調(diào)用來(lái)檢查您正在測(cè)試的方法是否使用了 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 中看起來(lái)正確的 Mockito 異常的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!