androidkotlinandroid-testingandroidxandroid-fragmentscenario

Error inflating class com.google.android.material.tabs.TabLayout inside FragmentScenario test


I wrote a test using FragmentScenario:

@Test
fun test() {
    launchFragmentInContainer<MyFragment>(Bundle().apply { putParcelableArray(MY_DATA, getMyData()) })
    // checks here
}

However, I get following error:

Error inflating class com.google.android.material.tabs.TabLayout

I only get the error when I launch my test (the app works). I tried to add "com.google.android.material:material:1.0.0" to androidTestImplementation but it didn't help.

What can I do to fix this?


Solution

  • The default theme for the activity that FragmentScenario launches has a parent theme of android:Theme.WithActionBar - not the MaterialComponents theme that TabLayout requires.

    You should pass in the theme that you want to use.

    For example, assuming your app has a theme declared as such:

    <style name="AppTheme" parent="Theme.MaterialComponents">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    

    You'd use:

    launchFragmentInContainer<MyFragment>(
        Bundle().apply { putParcelableArray(MY_DATA, getMyData()) },
        R.style.AppTheme
    )