在 FragmentScenario 测试中膨胀 class com.google.android.material.tabs.TabLayout 时出错

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

我用 FragmentScenario 写了一个测试:

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

我收到以下错误:

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

而且我只有在启动测试时才会收到错误消息(应用程序可以运行) 我尝试将 androidTestImplementation "com.google.android.material:material:1.0.0" 添加到 androidTestImplementation 但它没有帮助

我该怎么做才能解决这个问题?

activity FragmentScenario 发布的默认主题有父主题 android:Theme.WithActionBar - 而不是 TabLayout 需要的 MaterialComponents 主题。

您应该传入要使用的主题。

例如,假设您的应用有一个这样声明的主题:

<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>

你会使用:

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