-->

Robolectric AndroidX fragments NoClassDefFoundErro

2020-08-13 05:41发布

问题:

After migration of code and tests to AndroidX, all seems to work pretty well, however Robolectric junit tests for two fragments are failing due to NoClassDefFoundError: androidx/fragment/testing/R$style exception. The stack trace:

java.lang.NoClassDefFoundError: androidx/fragment/testing/R$style at androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity.onCreate(FragmentScenario.java:79) at android.app.Activity.performCreate(Activity.java:5933) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) at androidx.test.runner.MonitoringInstrumentation.callActivityOnCreate(MonitoringInstrumentation.java:674) at org.robolectric.android.controller.ActivityController.lambda$create$0(ActivityController.java:69) at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:365) at org.robolectric.android.controller.ActivityController.create(ActivityController.java:69) at org.robolectric.android.controller.ActivityController.create(ActivityController.java:74) at org.robolectric.android.internal.LocalActivityInvoker.startActivity(LocalActivityInvoker.java:39) at androidx.test.core.app.ActivityScenario.launch(ActivityScenario.java:207) at androidx.fragment.app.testing.FragmentScenario.internalLaunch(FragmentScenario.java:283) at androidx.fragment.app.testing.FragmentScenario.launchInContainer(FragmentScenario.java:265)

For testing fragments I'm using FragmentScenario, and it seems the FragmentScenario.EmptyFragmentActivity refers to a missing R class from a package androidx.fragment.testing.R:

setTheme(getIntent().getIntExtra(THEME_EXTRAS_BUNDLE_KEY, R.style.FragmentScenarioEmptyFragmentActivityTheme));

Any idea what might be wrong? Maybe I'm missing a dependency that's not that obvious to me.

Reproducible in following project: https://github.com/marcinbak/androidx-test-error

Also reported in Google's issue tracker: https://issuetracker.google.com/issues/122321150

回答1:

According to answer from Google it is required to include androidx_fragment_test (androidx.fragment:fragment-testing:1.1.0-alpha03) artifact in the testing APK (not in instrumentation APK or testing dependency).

What this means it has to be added as debugImplementation androix_fragment_test in your build.gradle file.

If you also run tests on release target then you have to add implementation androix_fragment_test.

You can see the whole conversation in Google's issue tracker: https://issuetracker.google.com/issues/122321150