2017-04-18 6 views
1

私はPowermockの使い方を理解しようとしています。 私はhereを模倣したStaticメソッドの例を実現しようとしています。Powermock:NoClassDefFoundError静的クラスをモックしようとしています

私は上記の例に基づいてこのコードを作成しました。

ただし、テストを実行しようとするとNoClassDefFoundErrorが発生します。

ほとんどの場合、貼り付け済みのコードであるため、このエラーの原因を正確にはわかりません。

// 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は、私はあなたのpom.xmlにいくつかの変更を加えましたMockito 2.7

と互換性があるように思われます。最初に私はpowermockバージョンを変更:

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

その後、私は(最初のものは動作しませんでした、Mockito 2.7と互換性があると思われる)powermock-api-mockito2powermock-api-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

クラスパスはどのように設定されていますか? –

+0

'NoClassDefFoundError'のstacktraceはあなたに欠けているクラスを示していますか? –

関連する問題