易错的Android Espresso测试 - Snackbar

14

1) 所有正在测试的设备/模拟器都已禁用动画。

2) 我有一个 @BeforeClass 方法,用于构建我的 Credentials 对象。

3) 我有一个 IntenServiceIdlingResource 和 EventBusIdlingResource,在 @Before 中注册。

4) 当点击登录按钮时,IntentService 会触发。在这种情况下,服务器(模拟服务器)返回 500 错误。该信息通过 greenrobot 的 EventBus 从 IntentService 发送回 UI,并显示一个包含错误消息的 Snackbar。

这是测试的代码:

@Test
public void a_userNamePasswordTest() throws Exception {
    // email input
    ViewInteraction userNameView = onView(withId(R.id.email));

    // verify it's on screen and enabled
    userNameView.check(matches(isDisplayed())).check(matches(isEnabled()));

    // set the username
    userNameView.perform(scrollTo(), replaceText(credentials.username), closeSoftKeyboard());

    // password input
    ViewInteraction passwordView = onView(withId(R.id.password));

    // verify it's on screen and enabled
    passwordView.check(matches(isDisplayed())).check(matches(isEnabled()));

    // set the password.
    passwordView.perform(scrollTo(), replaceText(credentials.password), closeSoftKeyboard());

    // sign in button
    ViewInteraction signInButton = onView(withId(R.id.email_sign_in_button));

    // verify the button
    signInButton.check(matches(allOf(
            isDisplayed(), isEnabled(), withText("Sign In"), withContentDescription("Sign In")
    )));

    // clickity click the button
    signInButton.perform(scrollTo(), click());

    // verify the snackbar text
    onView(withText(startsWith("Server Error: 500"))).check(matches(isDisplayed()));

}

这是我通常遇到的异常:

SignInExceptionTest > a_userNamePasswordTest[Nexus_6P_API_23(AVD) - 6.0] 失败 android.support.test.espresso.NoMatchingViewException: 找不到匹配的层次结构中的视图:带有文本的字符串,以"Server Error: 500" 开头

根据我的日志记录,我的空闲资源在工作。但是查看日志的时间戳,异常似乎是在空闲资源空闲后约5秒发生的。

看起来在资源空闲后,它尝试查找视图时存在延迟。

其他可能相关的细节:

  • minSdk: 20
  • compile & targetSdk: 25
  • buildTools: 25.0.2
  • support-library: 25.1.1
  • espresso-core: 2.2.2
  • gradle插件2.3.0-beta3

除了增加展示 snackbar 的时间之外,如何修复此测试,使其不那么脆弱?

1个回答

16

Espresso会在IdlingResource变得活跃后等待5秒钟,然后再次检查其是否空闲。

这对我来说有2个负面影响。

首先,它增加了测试运行的时间。每个测试都额外多5秒(或5的倍数),真的会累加起来。

其次,由于snackbar立即显示,并且只显示约3.5秒钟,在等待IdlingResource时,几乎任何时候,snackbar在Espresso意识到资源已空闲之前就已经消失了,这使得测试变得困难。

ConditionWatcher在这里描述: https://medium.com/azimolabs/wait-for-it-idlingresource-and-conditionwatcher-602055f32356#.9rms52osh

并且代码在这里: https://github.com/AzimoLabs/ConditionWatcher

提供了解决这两个问题的方法。它默认为250毫秒而不是5秒,并且可以调整此值(使用setWatchInterval)。


谢谢。Espresso对IdlingResource的依赖让我感到非常恼火。将测试框架代码散布到我的类中是没有好理由的,这应该是正确的做法。我仍然无法相信Espresso还没有像这样的东西! - Captain Blammo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接