I am building an android application which I want to unit test with JUnit tests, not the Android JUnit tests (because it takes way too long to run the Android tests with the emulator).
Environment:
- Eclipse
- Android project
- Android test project (target package = android project package)
- JUnit4 / Mockito
- Running unit tests with JUnit (deliberately not Android JUnit)
As long as I test my own written classes that have no dependencies on Android classes, all goes well. But when I want to write a test for a class that contains e.g. a Log.i()
statement or refers to a TextView
, then I run into the following error:
java.lang.NoClassDefFoundError: android/text/TextWatcher at java.lang.ClassLoader.defineClass1(Native Method)
Android application manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cleancode.lifesaver"
android:versionCode="1"
android:versionName="1.0" >
Android test project manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cleancode.lifesaver.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.cleancode.lifesaver" />
Class to test:
import android.widget.TextView;
public class CapCharacterTextValidator extends TextValidator {
public CapCharacterTextValidator(TextView textView) {
super(textView);
}
@Override
public void validate(TextView textView, String text) {
}
}
Test class:
import org.junit.Test;
import com.cleancode.lifesaver.utils.CapCharacterTextValidator;
public class CapCharactersTextValidatorTests {
@Test
public void validateCharacters() {
new CapCharacterTextValidator(null);
}
}
I tried to add the android library in the exported libraries in both the Android application and the Android test application, or one of the two, still nothing gives me a green test. No matter what I try, I keep running into this NoClassDefFoundError
.
I read most of the android documentation but they seem to be really fond of the (for me too slow) approach with Android JUnit on the emulator.
Nor do the following Q&A posts help me further:
- Android JUnit testing ClassNotFoundException
- java.lang.NoClassDefFoundError while running JUnit test in Netbeans
- Eclipse + Android + JUnit test references android.os class = NoClassDefFoundError
Any help would be greatly appreciated!