How to test AndroidX fragment with Robolectric?
I added testImplementation "org.robolectric:shadows-supportv4:4.0-alpha-3"
dependency and tried with this code:
val controller = SupportFragmentController.setupFragment(
TestableFragment.buildFragment(DATA),
TestableFragmentHolderActivity::class.java)
TestableFragment
is androidx.fragment.app.Fragment
, and TestableFragmentHolderActivity
is androidx.appcompat.app.AppCompatActivity
But I get an error during test:
java.lang.NoSuchMethodError: org.robolectric.shadows.support.v4.SupportFragmentController.setupFragment(Landroidx/fragment/app/Fragment;Ljava/lang/Class;)Landroidx/fragment/app/Fragment;
There is a new way to test fragments with Robolectric's latest API. Check the official doc
You'll need to create a FragmentScenario
val fragmentScenario = launchFragmentInContainer<MyFragment>()
and then test like you usually do with Espresso
onView(withId(R.id.text)).check(matches(withText("Hello World!")))
Kindly refer to this git issue: https://github.com/robolectric/robolectric/issues/3985. New API for AndroidX fragment will be soon released.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With