[英]Nested mocking in Mockito
I have this Mockito code: 我有这个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");
}
}
The last when()
throws the following exception: 最后一个
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)
However, I am NOT mocking return value for Dao.doSomething
, but for LegacyClass.legacyMethod()
. 但是,我
Dao.doSomething
为Dao.doSomething
嘲笑返回值,而是为了LegacyClass.legacyMethod()
。
Is this the expected behavior? 这是预期的行为吗? Are there any Mockito docs stating you cannot nest mocks like this?
是否有任何Mockito文件声明你不能像这样嵌套嘲笑?
How can I walk this around? 我该怎么走这个?
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 calls dao.doSomething()
), that's why you are getting this error. 在您的示例代码中,真正的方法
legacy.legacyMethod()
实际上被调用,因为它是间谍而不是模拟(然后调用dao.doSomething()
),这就是您收到此错误的原因。
If you want to make a partial mock, you have to write this as : 如果你想进行局部模拟,你必须把它写成:
doReturn("Replacement").when(legacy).legacyMethod();
That way Mockito will know that you want to make a partial mock, so it won't call the real method. 这样Mockito就会知道你想要进行局部模拟,所以它不会调用真正的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.