androidfragmentandroidxrobolectricandroid-fragmentscenario

Testing AndroidX fragments on JVM only (without launching an emulator/device)


I'm looking for a way to unit test my AndroidX fragments without the need launch the fragment in an emulator. Robolectric allows us to run our unit tests for activities in the JVM, but I'm not sure what the equivalent approach is for AndroidX fragments.

Google Android recently introduced FragmentScenario, which allows us to launch and test graphical fragments, but this approach launches the fragment on a device/emulator (similar to ActivityScenario). The Robolectric website seems to endorse this way of launching fragments.

Is it possible—via Robolectric or otherwise—to run AndroidX fragment unit tests purely on the JVM (no emulator/device)?


Solution

  • It looks like fragmentScenario can be used in Robolectric tests and they run on the JVM. See the end of this article: https://proandroiddev.com/isolated-fragments-unit-tests-that-run-both-instrumented-and-on-the-jvm-with-the-same-source-code-283db2e9be5d