Espresso - 使用异步加载的数据断言TextView

Bol*_*oso 14 android android-testing android-espresso

我正在使用谷歌Espresso for Android编写UI测试,我一直坚持如何断言TextView文本,这些内容是从Web服务异步加载的.我目前的代码是:

public class MyTest extends BaseTestCase<MyActivity>{
    public void setUp() throws Exception {
        // (1) Tell the activity to load 'element-to-be-loaded' from webservice
        this.setActivityIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("data://data/element-to-be-loaded")));
        getActivity();

        super.setUp();
    }

    public void testClickOnReviews(){
        // (2) Check the element is loaded and its name is displayed
        Espresso
            .onView(ViewMatchers.withId(R.id.element_name))
            .check(ViewAssertions.matches(ViewMatchers.withText("My Name")));

        // (3) Click on the details box
        Espresso
            .onView(ViewMatchers.withId(R.id.details_box))
            .check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
            .perform(ViewActions.click());

        // (4) Wait for the details screen to open
        Espresso
            .onView(ViewMatchers.withId(R.id.review_box));

        // Go back to element screen
        Espresso.pressBack();
    }
}
Run Code Online (Sandbox Code Playgroud)

在(1)上,我通知我的活动从webservice加载一个元素.在(2),我正在等待断言其内容的观点.这是测试失败的部分,因为它在webservice应答应用之前执行.

如何告诉Espresso等待屏幕上显示特定数据?或者我应该以不同的方式思考这样的测试?

Val*_*rov 19

您可以通过使用Espresso为您的Web服务注册IdlingResource来处理这种情况.看一下这篇文章:https://developer.android.com/training/testing/espresso/idling-resource.html

最有可能的是,你会想要使用CountingIdlingResource(它使用一个简单的计数器来跟踪某些东西是空闲的).此示例测试演示了如何完成此操作.