Mockito 中的嵌套模拟
我有这个 Mockito 代码:
interface Dao {
public void doSomething();
}
class LegacyClass {
Dao dao;
public String legacyMethod() {
dao.doSomething();
return "Test";
}
}
public class MockitoTest {
public static void main(String[] args) {
Dao dao = mock(Dao.class);
LegacyClass legacyInst = new LegacyClass();
legacyInst.dao = dao;
LegacyClass legacy = spy(legacyInst);
when(legacy.legacyMethod()).thenReturn("Replacement");
}
}
最后一个 when()
抛出以下异常:
Exception in thread "main" org.mockito.exceptions.base.MockitoException:
'doSomething' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
If the method you are trying to stub is *overloaded* then make sure you are calling the right overloaded version.
at mypkg.MockitoTest.main(MockitoTest.java:28)
但是,我不是在模拟 Dao.doSomething
的返回值,而是在模拟 LegacyClass 的返回值。遗留方法()。
这是预期的行为吗?是否有任何 Mockito 文档说明您不能像这样嵌套模拟?
我该如何解决这个问题?
I have this Mockito code:
interface Dao {
public void doSomething();
}
class LegacyClass {
Dao dao;
public String legacyMethod() {
dao.doSomething();
return "Test";
}
}
public class MockitoTest {
public static void main(String[] args) {
Dao dao = mock(Dao.class);
LegacyClass legacyInst = new LegacyClass();
legacyInst.dao = dao;
LegacyClass legacy = spy(legacyInst);
when(legacy.legacyMethod()).thenReturn("Replacement");
}
}
The last when()
throws the following exception:
Exception in thread "main" org.mockito.exceptions.base.MockitoException:
'doSomething' is a *void method* and it *cannot* be stubbed with a *return value*!
Voids are usually stubbed with Throwables:
doThrow(exception).when(mock).someVoidMethod();
If the method you are trying to stub is *overloaded* then make sure you are calling the right overloaded version.
at mypkg.MockitoTest.main(MockitoTest.java:28)
However, I am NOT mocking return value for Dao.doSomething
, but for LegacyClass.legacyMethod()
.
Is this the expected behavior? Are there any Mockito docs stating you cannot nest mocks like this?
How can I walk this around?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
间谍不是这样工作的。在您的示例代码中,实际上调用了真正的方法
legacy.legacyMethod()
,因为它是间谍而不是模拟(然后调用dao.doSomething()
),这就是为什么你收到这个错误。如果你想进行部分模拟,你必须将其写为:
这样 Mockito 就会知道你想要进行部分模拟,因此它不会调用真正的方法。
Spies don't work this way. In your sample code, the real method
legacy.legacyMethod()
is actually called because it's a spy not a mock (which then callsdao.doSomething()
), that's why you are getting this error.If you want to make a partial mock, you have to write this as :
That way Mockito will know that you want to make a partial mock, so it won't call the real method.