java.lang.NoClassDefFoundError while running JUnit

2019-02-16 10:48发布

问题:

I am building an Android hello world application in Netbeans. It's building properly and I am able to run in the emulator also.

But when creating and running the Junit test I get a java.lang.NoClassDefFoundError.

How can I fix this problem?

回答1:

Check the manifest of your test project, for example HelloWorldTest/AndroidManifest.xml. The android:targetPackage attribute of the instrumentation markup should target the package in your application, for example, com.example.helloworld. Not the test package of your test project (eg. com.example.helloworld.test).



回答2:

Simply AndroidManifest.xml -> manifest -> package of main application should match AndroidManifest.xml -> manifest -> instrumentation -> android:targetPackage of the test application.



回答3:

The full error message contains the name of the class, that wasn't found on the classpath. Double check if the classpath that is used for running the test includes all required classes and libraries (your class files, junit.jar, android specific libaries).



回答4:

I find that a rebuild usually finds the classes (as it is a classpath issue). Netbeans seems to aggressively compile existing tests, but the main source code (from a maven setting at least) is not always available.

I've started running full builds to try address this. There might be a plugin that addresses this but I haven't found it yet.

EDIT: This might help.



回答5:

I don't know about netbeans specifics, but the problem is probably the same.

FragmentActivity can not be tested via ActivityInstrumentationTestCase2

Your test project can be using a different android compatibility library than your main project, and that causes this weird errors.