doThrow 中看起来正确的 Mockito 异常
我正在尝试模拟一个方法以查看我是否正确处理了异常.这是据我所知.
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);
结果:
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()
其他地方?无论如何,这在我的情况下导致了这个问题.
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
一起使用的存根的参数之一是您也模拟的方法的结果,那么 Mockito 会感到不安.也许这是一种避免无限循环的重入检查,我不知道.
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()
替换为常量值,这应该可以解决问题.您可以考虑使用在测试中声明的常量来进行模拟和任何进一步的使用.然后,您还可以通过添加另一个对 verify
的调用来检查您正在测试的方法是否使用了 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
.
相关文章