Junit Mockito没有按预期进行模拟测试

4

我正在尝试通过模拟一些方法来编写单元测试。但是我遇到了一些问题,我认为其中一个对象没有被模拟。

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(),但实际上我已经模拟了调用该方法的输出,所以不应该再次调用它。
1个回答

4

Mockito.when会调用真实方法。为了解决这个问题,你可以使用Mockito.doReturn代替:

Mockito.doReturn(true).when(spyTestObj).internalMethod(Mockito.anyString());
Mockito.doReturn(true).when(spyTestObj.c).someMethod(Mockito.anyBoolean());

请注意,通常不需要模拟调用被监视对象上的真实方法 - 这是默认行为。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接