Mockito exception in doThrow that looks correct(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
.
这篇关于doThrow 中看起来正确的 Mockito 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:doThrow 中看起来正确的 Mockito 异常


基础教程推荐
- 从 python 访问 JVM 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01