2017-04-18 44 views
1

我試圖瞭解如何使用Powermock。 我試圖實現靜態方法嘲諷here的例子。Powermock:NoClassDefFoundError嘗試模擬靜態類

我根據上面的例子創建了這段代碼。

但是當我嘗試運行測試時,我得到了一個N​​oClassDefFoundError。

我不知道到底是什麼導致了這個錯誤,因爲它主要是複製粘貼代碼。

// imports redacted 

@RunWith(PowerMockRunner.class) 
@PrepareForTest(Static.class) 
public class YourTestCase { 
    @Test 
    public void testMethodThatCallsStaticMethod() throws Exception { 
     // mock all the static methods in a class called "Static" 
     PowerMockito.mockStatic(Static.class); 
     // use Mockito to set up your expectation 
     PowerMockito.when(Static.class, "firstStaticMethod", any()).thenReturn(true); 
     PowerMockito.when(Static.class, "secondStaticMethod", any()).thenReturn(321); 

     // execute your test 
     new ClassCallStaticMethodObj().execute(); 

     // Different from Mockito, always use PowerMockito.verifyStatic() first 
     // to start verifying behavior 
     PowerMockito.verifyStatic(Mockito.times(2)); 
     // IMPORTANT: Call the static method you want to verify 
     Static.firstStaticMethod(anyInt()); 


     // IMPORTANT: You need to call verifyStatic() per method verification, 
     // so call verifyStatic() again 
     PowerMockito.verifyStatic(); // default times is once 
     // Again call the static method which is being verified 
     Static.secondStaticMethod(); 

     // Again, remember to call verifyStatic() 
     PowerMockito.verifyStatic(Mockito.never()); 
     // And again call the static method. 
     Static.thirdStaticMethod(); 
    } 
} 

class Static { 
    public static boolean firstStaticMethod(int foo) { 
     return true; 
    } 

    public static int secondStaticMethod() { 
     return 123; 
    } 

    public static void thirdStaticMethod() { 
    } 
} 

class ClassCallStaticMethodObj { 
    public void execute() { 
     boolean foo = Static.firstStaticMethod(2); 
     int bar = Static.secondStaticMethod(); 
    } 
} 

回答

3

PowerMock 1.6.6似乎是不符合2.7的Mockito

我做了一些更改pom.xml。首先,我改變了powermock版本:

<powermock.version>1.7.0RC2</powermock.version> 

然後,我改變powermock-api-mockitopowermock-api-mockito2(第一個沒有工作,這似乎是一個2.7的Mockito不兼容):

<dependency> 
    <groupId>org.powermock</groupId> 
    <artifactId>powermock-api-mockito2</artifactId> 
    <version>${powermock.version}</version> 
    <scope>test</scope> 
</dependency> 

這解決了NoClassDefFoundError


不管怎樣,我還是不得不改變這使其工作:不是PowerMockito.when(),你應該使用Mockito.when()

Mockito.when(Static.firstStaticMethod(anyInt())).thenReturn(true); 
Mockito.when(Static.secondStaticMethod()).thenReturn(321); 
+0

可悲的是沒有解決的NoClassDefFoundError錯誤。 – Philippe

+0

你的classpath是如何設置的? – 2017-04-19 09:57:43

+0

'NoClassDefFoundError'堆棧跟蹤是否顯示缺少的類? – 2017-04-19 11:48:08