Espresso - 使用异步加载的数据断言 TextView
Posted
技术标签:
【中文标题】Espresso - 使用异步加载的数据断言 TextView【英文标题】:Espresso - Asserting a TextView with async loaded data 【发布时间】:2014-01-08 19:11:56 【问题描述】:我正在使用适用于 android 的 Google Espresso 编写 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();
在 (1) 上,我通知我的活动从 Web 服务加载元素。在 (2) 上,我正在等待断言其内容的视图。这是测试失败的部分,因为它在 web 服务响应应用程序之前执行。
如何让 Espresso 等待特定数据出现在屏幕上?或者我应该以不同的方式来编写这样的测试?
【问题讨论】:
尝试这种方法 - ***.com/a/22563297/349681,您可能可以使用负匹配器并等到视图消失。 【参考方案1】:您可以通过使用 Espresso 为您的 Web 服务注册 IdlingResource 来处理这种情况。看看这篇文章:https://developer.android.com/training/testing/espresso/idling-resource.html
您很可能会想要使用CountingIdlingResource(它使用一个简单的计数器来跟踪某事何时空闲)。这个sample test 演示了如何做到这一点。
【讨论】:
太棒了!明天我一定会试一试。文档说 Espresso 绑定到 AsyncTask 线程池。它是由 AsyncTaskPoolMonitor 完成的吗? Volley 线程池有什么开箱即用的功能吗? Volley 还没有。如果开源社区的某个人能做出贡献,那就太好了。对此进行了一些讨论:groups.google.com/forum/#!searchin/android-test-kit-discuss/…【参考方案2】:如果您不介意将 UiAutomator 与 Espresso 一起使用,您可以在步骤 4 中执行类似的操作。
UiObject object = mDevice.findObject(new UiSelector().resourceId(packageName + ":id/" + "review_box"));
object.waitForExists(5000);
https://developer.android.com/reference/android/support/test/uiautomator/UiObject.html#waitForExists(long)
【讨论】:
以上是关于Espresso - 使用异步加载的数据断言 TextView的主要内容,如果未能解决你的问题,请参考以下文章
如何在没有 IdlingResource 的情况下在 Espresso 中等待异步任务
Espresso:如何测试 SwipeRefreshLayout?
Android Espresso,RecyclerViewActions 请求权限
Android Studio 2.2 Espresso Test Recorder-----解放双手,通过录制测试过程实现测试