我试图通过模拟某些方法来编写单元测试.但是,我遇到了一些问题,其中我认为其中一个对象没有被嘲笑.
class A {
Class_C c;
Class A(String x) {
c = new Class_C(x);
}
public boolean internalMethod(String internalInput) {
// Some Logic
// Calls Inet4Address.getByName(internalInput)
}
public boolean method_to_be_tested(String input) {
boolean result_1 = internalMethod(input);
boolean result_2 = c.someMethod(result_1);
}
}
我写的单元测试如下:
@Test
public void test_method_to_be_tested() {
A testObj = new A("test_input");
testObj.c = Mockito.mock(Class_C.class);
A spyTestObj = Mockito.spy(testObj);
Mockito.when(spyTestObj.internalMethod(Mockito.anyString())).thenReturn(true);
Mockito.when(spyTestObj.c.someMethod(Mockito.anyBoolean())).thenReturn(true);
Mockito.when(spyTestObj.test_method_to_be_tested("test_input")).thenCallRealMethod();
Assert.assertTrue(spyTestObj.test_method_to_be_tested("test_input"));
}
我收到的错误指示Inet4Address.getByName()正在被调用.不应这样,因为我已经模拟了调用它的方法的输出.
解决方法:
Mockito.when将调用real方法.要解决此问题,可以改用Mockito.doReturn:
Mockito.doReturn(true).when(spyTestObj).internalMethod(Mockito.anyString());
Mockito.doReturn(true).when(spyTestObj.c).someMethod(Mockito.anyBoolean());
请注意,通常无需模拟对侦听对象的real方法-这始终是默认行为.