在同一 class 中调用内部测试方法的模拟方法

Mock method called inside testing method in same class

 public class MyClass {

   public int result(){
     int result = calculate(new ValueProvider());
          return result;
      }

   public int calculate(ValueProvider provider){
            return provider.getSalary();
      }

}

public class ValueProvider {

    public int getSalary(){
        return 10000000;
    }
}

我需要测试方法 result(),但必须模拟第二个方法计算哪个应该 return 默认值。

使用 Mockito spy 创建部分模拟。

例如:

public class TestMyClass {

    @Test
    public void aTest() {
        MyClass spy = Mockito.spy(MyClass.class);

        // this will cause MyClass.calculate() to return 5 when it 
        // is invoked with *any* instance of ValueProvider
        Mockito.doReturn(5).when(spy).calculate(Mockito.any(ValueProvider.class));

        Assert.assertEquals(123, spy.result());
    }
}

在此测试用例中,对 calculate 的调用是模拟的,但对 result 的调用是真实的。来自 the docs:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).