我正在尝试通过模拟一些方法来编写单元测试。但是我遇到了一些问题,我认为其中一个对象没有被模拟。
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()
,但实际上我已经模拟了调用该方法的输出,所以不应该再次调用它。