junit Robolectric 4.4单元测试错误-主活套已将未执行的可运行项排队

yb3bgrhw  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(169)

此的公寓测试错误

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.

我们正在使用Robolectric 4.4编译目标29,但确保在运行单元测试时目标28,因为JDK仍然是8而不是9。下面是一个代码块,但我似乎无法在任何地方添加循环器的idle()来使其满意

@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)
    }
.....
}
xoefb8l8

xoefb8l81#

添加一个InstantTaskExecutorRule解决了我的一个问题。

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

class Test {

    @get:Rule
    val executorRule = InstantTaskExecutorRule()

}

相关问题