JPM
JPM

Reputation: 9306

Robolectric 4.4 Unit Test Error - Main looper has queued unexecuted runnables

Unit test errors with this

Called loadFromPath(/system/framework/framework-res.apk, true); mode=binary sdk=28
java.lang.Exception: Main looper has queued unexecuted runnables. 
This might be the cause of the test failure. You might need a shadowOf(getMainLooper()).idle() call.

We are using Robolectric 4.4 compiling to target 29 but making sure we target 28 when running Unit tests due JDK still at 8 and not 9. Here is a block of code but I cannot seem to add the idle() for loopers in any place to make this happy

@RunWith(AndroidJUnit4::class)
@LooperMode(LooperMode.Mode.PAUSED)
class MyRoomActivityTest {

    @get:Rule
    val activityRule = ActivityTestRule(MyRoomActivity::class.java, true, false)

    @Inject lateinit var mockViewModel: NewMyRoomActivityViewModel

    @Inject lateinit var locationManager: LocationManager

    private var testViewStateLiveData: MutableLiveData<NewMyRoomActivityViewModel.MyRoomActivityViewState> = MutableLiveData()

    @Before
    fun setUp() {
        RobolectricTestGEComponent.GraphHolder.testGraph.inject(this)
        whenever(mockViewModel.viewState).thenReturn(testViewStateLiveData)
        shadowOf(getMainLooper()).idle() // doesn't work here
    }

    @Test
    fun `launch activity sets ViewModel room Id`() {
        val roomId = "TestMyRoomId"
        shadowOf(getMainLooper()).idle() // doesn't work here either 
        activityRule.launchActivity(MyRoomActivity.newIntent(ApplicationProvider.getApplicationContext(), roomId))  // fails here all the time
        verify(mockViewModel).initialize(roomId)
    }
.....
}

Upvotes: 14

Views: 10882

Answers (1)

Goltsev Eugene
Goltsev Eugene

Reputation: 3637

Adding an InstantTaskExecutorRule solved an issue for me.

import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import org.junit.Rule

class Test {

    @get:Rule
    val executorRule = InstantTaskExecutorRule()

}

Upvotes: 1

Related Questions