简体   繁体   English

Junit Mockito没有像预期的那样嘲笑

[英]Junit Mockito not mocking as expected

I am trying to write a unit testing by mocking some of the methods. 我试图通过模拟一些方法来编写单元测试。 I am however facing some issue, wherein I believe one of the objects is not getting mocked. 然而,我面临一些问题,其中我认为其中一个对象没有被嘲笑。

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);

   }
}

The unit test I have written is as below: 我写的单元测试如下:

 @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"));
 }

The error I am getting indicates Inet4Address.getByName() is getting invoked. 我得到的错误表明调用了Inet4Address.getByName() It should not be since I have mocked out the output of the method in which it is called. 它不应该是因为我已经模拟了调用它的方法的输出。

Mockito.when will invoke the real method. Mockito.when会调用真正的方法。 To work around this, you can use Mockito.doReturn instead: 要解决此问题,您可以改为使用Mockito.doReturn

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

Note that there's usually no need to mock calling the real method on a spied object - that's the default behavior anyway. 请注意,通常不需要模拟在spied对象上调用实际方法 - 这仍然是默认行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM