2014-08-29 255 views
0

此代码嘲笑类中的静态void方法并覆盖其行为。Powermockito:拦截所有静态方法

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

我如何可以拦截所有的方法调用,而不是单独指定的方法(从这个问题here两者)​​?

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

回答

0

此:

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

不起作用,因为Matchers.anything()Object和上述when()创建匹配试图找到基于该类型的方法。尝试通过而不是Matchers.any(String.class)。这只适用于具有相同参数列表的静态方法。不知道是否有办法做出更通用的覆盖。

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

希望它可以帮助你。

+0

没有。不起作用。 – 2014-08-29 08:23:36