使用CountingIdlingResource进行异步操作时,检测测试失败

时间:2018-06-08 17:52:37

标签: android kotlin android-espresso android-instrumentation

在我的检测测试中,testZoomControls总是在CountingIdlingResource递减并导致map has not been initialized异常之前执行。

怎么可能?

MapViewUiControlsTest.kt

@RunWith(AndroidJUnit4::class)
class MapViewUiControlsTest {

    private lateinit var mapView: MapView
    private lateinit var map: Map

    @Rule
    @JvmField
    val activityRule: ActivityTestRule<MapViewTestActivity> = ActivityTestRule(
        MapViewTestActivity::class.java
    )

    @Rule
    @JvmField
    val grantPermissionRule: GrantPermissionRule =
        GrantPermissionRule.grant(android.Manifest.permission.ACCESS_FINE_LOCATION)

    private lateinit var idlingResource: CountingIdlingResource

    @Before
    @UiThreadTest
    fun init() {
        MockitoAnnotations.initMocks(this)

        idlingResource = activityRule.activity.idlingResource

        idlingResource.registerIdleTransitionCallback({
            map = activityRule.activity.map
            mapView = activityRule.activity.mapView
        })

        IdlingRegistry.getInstance().register(idlingResource)

        activityRule.activity.init()
    }

    @After
    @UiThreadTest
    fun cleanup() {
        IdlingRegistry.getInstance().unregister(idlingResource)
    }

    @Test
    @UiThreadTest
    fun testZoomControls() {
        map.getMapOptions().zoomControlsEnabled = true
        Assert.assertEquals(View.VISIBLE, mapView.zoomControlsView.visibility)
    }

}

MapViewTestActivity.kt

val idlingResource = CountingIdlingResource("dummy_resource", true)

fun init() {
    idlingResource.increment()
    mapView.getMapAsync(onMapReadyCallback = object : OnMapReadyCallback {
        override fun onMapReady(map: Map) {
            this@MapViewTestActivity.map = map
            idlingResource.decrement()
        }
    })
}

1 个答案:

答案 0 :(得分:0)

此IdlingResource需要Espresso.onView(..).check(..)或类似内容才能有所作为。在这种情况下,Espresso将等待所有IdlingRsources空闲,然后继续下一行代码:

@Test
@UiThreadTest
fun testZoomControls() {
    //this will wait until your IdlingResource is idle
    Espresso.onView(<your map view matcher>).check(matches(isDisplayed()));

    map.getMapOptions().zoomControlsEnabled = true
    Assert.assertEquals(View.VISIBLE, mapView.zoomControlsView.visibility)
}