Android Navigation Instrumentation test throws Method addObserver must be called on the main thread

Issue

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: Method addObserver must be called on the main thread.

My environment:

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?

Solution

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

Answered By – The_Martian

Leave a Comment