无法使用PowerMockito部分模拟静态方法

时间:2015-05-14 08:53:15

标签: junit mockito partial-mocks powermockito

我将在Util类中模拟一个名为 toBeMockedFunction 的静态函数。此方法从 toBeUnitTested 调用,这是一个公共静态void方法。我想要BeMockedFunction什么都不做。我尝试了许多部分模拟和存根的方法(这样的2个片段)并且无法成功。

请建议我做错了什么。

public class Util {
    // Some code
    public static void toBeUnitTested(CustomObject cb, CustomObject1 cb1, List<CustomObject2> rows, boolean delete) {
        // some code

       toBeMockedFunction(cb, "test", "test");
    }

    public static CustomObject toBeMockedFunction(CustomObject cb, String str1) {
        // some code
    }

}

以下是我的junit课程

@RunWith(PowerMockRunner.class)
 @PrepareForTest({ Util.class})
 public class UtilTest {
    @Test
    public void Test1() {
        PowerMockito.spy(Util.class);            

 //mock toBeMocked function and make it do nothing 
 PowerMockito.when(PowerMockito.spy(Util.toBeMockedFunction((CustomObject)Mockito.anyObject(), Mockito.anyString()))).thenReturn(null);

        Util.toBeUnitTested(cb, "test", "test");
     }
  }
  1. Approach2

      PowerMockito.mockStatic(Util.class);  
      PowerMockito.when(Util.toBeUnitTested((CustomObject)Mockito.anyObject(),Mockito.anyString())).thenCallRealMethod();
        Util.toBeUnitTested(cb, "test", "test");
    

1 个答案:

答案 0 :(得分:2)

这是如何做到这一点的一个例子:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Util.class})
public class UtilTest {
   @Test
   public void Test1() {

      PowerMockito.spy(Util.class);
      PowerMockito.doReturn(null).when(Util.class, "toBeMockedFunction", Mockito.any(CustomObject.class), Mockito.anyString(), Mockito.anyString());

      List<CustomObject2> customObject2List = new ArrayList<>();
      customObject2List.add(new CustomObject2());

      Util.toBeUnitTested(new CustomObject(), new CustomObject1(), customObject2List, true);
   }
}

请注意,OP的代码无法编译。方法toBeMockedFunction(CustomObject cb, String str1)只接收2个参数,而您使用3:toBeMockedFunction(cb, "test", "test");进行调用。如您所见,我已将最后一个添加到方法签名中。

希望有所帮助