2014-08-29 63 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