【问题标题】:Junit Mockito not mocking as expectedJunit Mockito 没有按预期嘲笑
【发布时间】: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


    【解决方案1】:

    Mockito.when 将调用真正的方法。要解决此问题,您可以改用Mockito.doReturn

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

    请注意,通常不需要模拟调用间谍对象的真实方法 - 无论如何,这是默认行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 1970-01-01
      • 2017-04-03
      • 2020-04-23
      • 1970-01-01
      • 2019-07-31
      相关资源
      最近更新 更多