Robolectric with AndroidX Fragments

Viewed 7088

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;

2 Answers

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!")))
Related