Android jUnit Test java.lang.NoClassDefFoundError: android/database/sqlite/SQLiteOpenHelper
Occasionally Android Studio does not correctly load Android classes into the classpath for testing. In our case it's usually android.os.Parcelable
. But the CI always works fine.
So running ./gradlew test
should always work in such occasions and with some luck fix the dependencies for Android Studio.
(This one has been confusing and infuriating me for a while now and I'm super glad I've finally got to the bottom of it!)
The first thing to note is that after running the following command in your project...
gradle clean build
... you should see a build/generated/mockable-android-XX.jar
file in your workspace. This file is generated by the mockableAndroidJar
Gradle Task which is run as part of the test
Gradle Task which is run as part of the build
Gradle Task.
The problem occurs when this file is missing from your workspace but Gradle unfortunately estimates the mockableAndroidJar
Task to be up to date and therefore skips executing it. You can verify this by running the following command...
gradle mockableAndroidJar --info
... and you'll see a message something as follows...
Skipping task ':Android:mockableAndroidJar' as it is up-to-date (took 0.001 secs).
The solution is to force run the mockableAndroidJar
Gradle Task which you can do by running the following command...
gradle mockableAndroidJar --rerun-tasks
... And Voila you should now see the build/generated/mockable-android-XX.jar
file reappear in your workspace and glad times your Android unit tests will be running again.
After facing this problem today, I'd like to share what I did to make it work again.
In your build.gradle file, add:
android {
...
testOptions {
unitTests.returnDefaultValues = true
}
}
and sync gradle files again. It should work now and the mockable android jar file should be generated. If you didn't have testOptions in your gradle file, just remove it and resync.
I hope it helps.