Android Navigation Instrumentation测试引发方法必须在主线程上调用方法addObserver [英] Android Navigation Instrumentation test throws Method addObserver must be called on the main thread

查看:215
本文介绍了Android Navigation Instrumentation测试引发方法必须在主线程上调用方法addObserver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个片段,一个是我图中的家庭片段.单击一个按钮后,用户将导航到第二个片段.通过将用户导航到第二个片段并显示文本,可以按预期工作.因此该图很好.

I have two Fragments, one being a home fragment in my graph. The User will be navigated to the second fragment upon clicking a button. It works as expected by navigating the user to the second fragment and displaying the text. So the graph is good.

现在我想编写一个仪器测试.

Now I wanted to write an instrumentation test.

@RunWith(AndroidJUnit4::class)
class TransitionTest {

    @Test
    fun testNavigationToSecondFragment() {
        
        val navController = TestNavHostController(
            ApplicationProvider.getApplicationContext())

        navController.setGraph(R.navigation.my_graph) <--throws exception

        // the rest of my test continues here
    }
}

但是,上面显示的用于设置图形的行引发了以下异常:

However, the line shown above to set the graph throws following exception:

IllegalStateException:必须在主方法上调用方法addObserver线程.

IllegalStateException: Method addObserver must be called on the main thread.

我的环境:

fragment_version = 1.2.5 nav_version = 2.3.1 espresso = 3.3.0

fragment_version = 1.2.5 nav_version = 2.3.1 espresso = 3.3.0

有人知道发生了什么以及如何解决吗?

Does anyone have any idea what is going on and how to solve it?

推荐答案

我将 setGraph 函数包装在 runOnUiThread 中,测试通过了.一旦找到真正的原因和更好的解决方案,我将更新答案.

I wrapped the setGraph function in runOnUiThread as such, and the test passes. I will update the answer once I find out the real cause and better solution.

runOnUiThread {
    navController.setGraph(R.navigation.my_graph)
}

这篇关于Android Navigation Instrumentation测试引发方法必须在主线程上调用方法addObserver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆