Powermockito:拦截所有静态方法

时间:2014-08-29 06:38:15

标签: java mockito powermock

此代码在类中模拟静态void方法并覆盖其行为。 (取自这个问题here

@RunWith(PowerMockRunner.class)
@PrepareForTest({Resource.class})
public class MockingTest{

    @Test
    public void shouldMockVoidStaticMethod() throws Exception {
        PowerMockito.spy(Resource.class);
        PowerMockito.doNothing().when(Resource.class, "readResources", Mockito.any(String.class));

        //no exception heeeeere!
        Resource.readResources("whatever");

        PowerMockito.verifyStatic();
        Resource.readResources("whatever");
    }
}

class Resource {
    public static void readResources(String someArgument) {
        throw new UnsupportedOperationException("meh!");
    }
    public static void read(String someArgument) {
        throw new UnsupportedOperationException("meh!");
    }
}

如何拦截所有方法调用而不是单独指定方法?

它尝试了PowerMockito.doNothing().when(Resource.class)PowerMockito.doNothing().when(Resource.class, Matchers.anything()),但这些都不起作用。

2 个答案:

答案 0 :(得分:0)

此:

PowerMockito.doNothing().when(Resource.class, Matchers.anything())

不起作用,因为Matchers.anything()Object创建了匹配器,而上述when()正在尝试根据类型查找方法。尝试传递Matchers.any(String.class)。这仅适用于具有相同参数列表的静态方法。不确定是否有办法进行更通用的覆盖。

答案 1 :(得分:0)

如果你想模拟一个类的所有静态方法,我认为你可以使用PowerMockito.mockStatic(..)而不是PowerMockito.spy(..)

   @Test
   public void shouldMockVoidStaticMethod() throws Exception {
      PowerMockito.mockStatic(Resource.class);

      //no exception heeeeere!
      Resource.readResources("whatever");

      PowerMockito.verifyStatic();
      Resource.readResources("whatever");
   }

希望它对你有所帮助。