NoClassDefFoundError when using Powermock

2019-01-23 11:58发布

I'm running a junit test case using the PowerMock test runner. I'm using the following command line to execute it:

java -cp .:junit-4.9b2.jar:easymock-3.0.jar:powermock-easymock-1.4.8-full.jar org.junit.runner.JUnitCore SampleTest

When doing so I am receiving this error:

initializationError(SampleTest)
java.lang.NoClassDefFoundError: org/junit/internal/runners/TestClassRunner
...

How can I fix it?

5条回答
家丑人穷心不美
2楼-- · 2019-01-23 12:12

I am using JUnit 4.0 - 4.3 and I updated my maven dependency to use powermockito 2.0.0-beta.5 version. It just started working.

 <dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.0-beta.5</version>
    <scope>test</scope>
 </dependency>
 <dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.0-beta.5</version>
    <scope>test</scope>
  </dependency>
查看更多
混吃等死
3楼-- · 2019-01-23 12:15

This Exception occurs when you Import the legacy version of PowerMockRunner.class when using JUnit 4.X or higher version since this legacy class is not available to run when using it with @RunWith annotation. I have solved this issue by replacing older legacy version import with the new version.

Incorrect Import:

import org.powermock.modules.junit4.legacy.PowerMockRunner;

Correct Import:

import org.powermock.modules.junit4.PowerMockRunner;
查看更多
等我变得足够好
4楼-- · 2019-01-23 12:27

I solved the problem. I used old version junit-4.0.jar. But I still don't understand why is missing the class TestClassRunner especially in the package powermock-easymock-junit-1.4.8.zip (there is junit-4.8.2.jar)? The junit-4.8.2.jar is missing the class TestClassRunner also.

查看更多
SAY GOODBYE
5楼-- · 2019-01-23 12:30

See here

You're probably using the wrong PowerMockRunner. There's one runner made for JUnit 4.4 and above and a second runner made for JUnit 4.0-4.3 (although the latter also works for some older minor versions of JUnit 4.4).
Try switching from the org.powermock.modules.junit4.PowerMockRunner to org.powermock.modules.junit4.legacy.PowerMockRunner or vice versa. Look at the getting started guide to see how to configure this in maven.

查看更多
Fickle 薄情
6楼-- · 2019-01-23 12:30

I just solved this one now, when I added the @RunWith(PowerMockRunner.class) attribute, eclipse automatically imported:

import org.powermock.modules.junit4.legacy.PowerMockRunner;

All I needed to do is change it to be:

import org.powermock.modules.junit4.PowerMockRunner;

And now it works fine with JUnit 4.8.2.

The 2nd runner is for when running with older versions of JUnit - specifically 4.3 and older.

查看更多
登录 后发表回答