Android Espresso IdlingResources 和 Fragment/Activity Transitions
Android Espresso IdlingResources and Fragment/Activity Transitions
我有一个 activity 承载片段 F1。单击按钮后,F1 将替换为另一个片段 F2。当按下后退按钮时,应用程序 returns 通过 退出过渡 动画从 F2 到 F1。
我的 Espresso 测试用例大致如下所示:
@Test
public void pressingBackRestorePreviousFragment() {
// we are in F1 and about to switch to F2
onView(withId(R.id.the_button)).perform(click());
// we are now in F2, pressing back should "return" to F1
Espresso.pressBack();
onView(withText("A specific text in F1")).check(matches(isDisplayed());
}
当测试用例运行s处于逐步调试模式时,上述测试通过。但在 正常 运行 模式 下,它失败了。只有当我在 onView(withText(__))
之前插入 Thread.sleep(___)
时,测试才会通过。
我认为更好的技术是将 Thread.sleep() 替换为 Espresso IdlingResource
,但我不确定如何将它与视图动画线程合并。理想情况下,我想将上面的测试用例重写为
@Test
public void pressingBackRestorePreviousFragment() {
// we are in F1 and about to switch to F2
onView(withId(R.id.the_button)).perform(click());
// we are now in F2, pressing back should "return" to F1
Espresso.pressBack();
onView(isRoot()).perform(waitForAnimCompletion());
onView(withText("A specific text in F1")).check(matches(isDisplayed());
}
Espresso 会等待主线程空闲后再执行操作。 Fragment
和 Activity
转换发生在主线程上,因此您不需要实现任何 IdlingResource
。这里发生的事情是,过渡动画导致 Espresso 主线程和测试线程的同步不稳定。如 Espresso setup instructions 中所述,您应该在用于测试的设备上禁用系统动画。
一般来说,Thread.sleep
语句对于测试来说是不好的做法,会导致测试不稳定和缓慢。 Espresso 的设计正是为了解决 Android 上的这个问题。查看 Valera Zakharov 在 GTAC 2013 上对问题的解释 when introducing Espresso。
我有一个 activity 承载片段 F1。单击按钮后,F1 将替换为另一个片段 F2。当按下后退按钮时,应用程序 returns 通过 退出过渡 动画从 F2 到 F1。
我的 Espresso 测试用例大致如下所示:
@Test
public void pressingBackRestorePreviousFragment() {
// we are in F1 and about to switch to F2
onView(withId(R.id.the_button)).perform(click());
// we are now in F2, pressing back should "return" to F1
Espresso.pressBack();
onView(withText("A specific text in F1")).check(matches(isDisplayed());
}
当测试用例运行s处于逐步调试模式时,上述测试通过。但在 正常 运行 模式 下,它失败了。只有当我在 onView(withText(__))
之前插入 Thread.sleep(___)
时,测试才会通过。
我认为更好的技术是将 Thread.sleep() 替换为 Espresso IdlingResource
,但我不确定如何将它与视图动画线程合并。理想情况下,我想将上面的测试用例重写为
@Test
public void pressingBackRestorePreviousFragment() {
// we are in F1 and about to switch to F2
onView(withId(R.id.the_button)).perform(click());
// we are now in F2, pressing back should "return" to F1
Espresso.pressBack();
onView(isRoot()).perform(waitForAnimCompletion());
onView(withText("A specific text in F1")).check(matches(isDisplayed());
}
Espresso 会等待主线程空闲后再执行操作。 Fragment
和 Activity
转换发生在主线程上,因此您不需要实现任何 IdlingResource
。这里发生的事情是,过渡动画导致 Espresso 主线程和测试线程的同步不稳定。如 Espresso setup instructions 中所述,您应该在用于测试的设备上禁用系统动画。
一般来说,Thread.sleep
语句对于测试来说是不好的做法,会导致测试不稳定和缓慢。 Espresso 的设计正是为了解决 Android 上的这个问题。查看 Valera Zakharov 在 GTAC 2013 上对问题的解释 when introducing Espresso。