首页 > 解决方案 > Android - 通过使用 launchFragmentInContainer 使用 Espresso 测试片段永远不会完成

问题描述

我的测试从未完成,我完全不知道为什么。我可以看到手机屏幕上显示的吐司。日志中绝对没有任何内容。

@RunWith(AndroidJUnit4::class)
@SmallTest
class BaseDataFragmentUITest
{
   @Test
   fun isDisplayingToastWhenFAILED_TO_UPDATE()
   {

    val fragmentScenario = launchFragmentInContainer<TestBaseDataFragmentImp>()
    val toastString: String = context.resources.getString(com.developerkurt.gamedatabase.R.string.data_update_fail)

  
    fragmentScenario.onFragment {
        it.handleDataStateChange(BaseRepository.DataState.FAILED_TO_UPDATE)
  
        onView(withText(toastString)).inRoot(withDecorView(not(it.requireActivity().getWindow().getDecorView()))).check(matches(isDisplayed()))

       }
    
   }
}

标签: androidunit-testingkotlintesting

解决方案


显然,不应在 onFragment 块内进行 Espresso 断言。因此,当我这样编写测试时,它起作用了:

    @Test
    fun isDisplayingToastWhenFAILED_TO_UPDATE()
    {

        val fragmentScenario = launchFragmentInContainer<TestBaseDataFragmentImp>()
        val toastString: String = context.resources.getString(com.developerkurt.gamedatabase.R.string.data_update_fail)

        var decorView: View? = null

        fragmentScenario.onFragment {
            it.handleDataStateChange(BaseRepository.DataState.FAILED_TO_UPDATE)
            decorView = it.requireActivity().getWindow().getDecorView()
        }
        
onView(withText(toastString)).inRoot(withDecorView(not(decorView!!))).check(matches(isDisplayed()))

    }

推荐阅读