【发布时间】:2016-10-15 20:30:04
【问题描述】:
我正在尝试通过模拟一些方法来编写单元测试。然而,我面临一些问题,我相信其中一个对象没有被嘲笑。
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() 正在被调用。不应该,因为我已经模拟了调用它的方法的输出。
【问题讨论】:
标签: java unit-testing junit mockito