首页 > 解决方案 > 根据条件禁用 Espresso IdlingResource

问题描述

我有以下浓缩咖啡测试:

    @Test
    fun testSearchItemFound() {
        onView(withId(R.id.action_search)).perform(click())

        onView(isAssignableFrom(EditText::class.java))
                .perform(typeText("Harry Potter"),
                        pressImeActionButton())

        // Check error message view is not displayed
        onView(withId(R.id.error_msg)).check(matches(not<View>(isDisplayed())))

        // Check the item we are looking for is in the search result list.
        onData(allOf(`is`<Any>(instanceOf<Any>(String::class.java)),
                withItemContent("Harry Potter")))
                .check(matches(isDisplayed()))
    }

第一行代码:

onView(withId(R.id.action_search)).perform(click())

将在 EspressoIdlingResource 空闲时正确执行。

但是最后一行代码:

onData(allOf(`is`<Any>(instanceOf<Any>(String::class.java)),
                withItemContent("Harry Potter")))
                .check(matches(isDisplayed())) 

当我们在 MainFragment 中有以下代码时将执行:

// The network request might be handled in a different thread so make sure Espresso knows
            // that the app is busy until the response is handled.
            EspressoIdlingResource.increment() // App is busy until further notice
            model.movies.observe(this@MainFragment, Observer<PagedList<Movie>> {

                // This callback may be called twice, once for the cache and once for loading
                // the data from the server API, so we check before decrementing, otherwise
                // it throws "Counter has been corrupted!" exception.
                if (!EspressoIdlingResource.getIdlingResource().isIdleNow) {
                    EspressoIdlingResource.decrement() // Set app as idle.
                }
                adapter.submitList(it)
            }) 

如果我禁用:

EspressoIdlingResource.increment() // App is busy until further notice

和 :

if (!EspressoIdlingResource.getIdlingResource().isIdleNow) {
                    EspressoIdlingResource.decrement() // Set app as idle.
                }

第一行正常工作:

onView(withId(R.id.action_search)).perform(click())

有没有办法处理这种特殊情况?

来源可以在:https ://github.com/Ali-Rezaei/TMDb-Paging/tree/master/app/src/androidTest/java/com/sample/android/tmdb

标签: androidandroid-espresso

解决方案


推荐阅读