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

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.

class TransitionTest {

    fun testNavigationToSecondFragment() {
        val navController = TestNavHostController(

        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?


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