Android Espresso 不等待片段加载

Android Espresso doesn't wait for fragments to load

我刚开始使用 Espresso 来测试 Android 应用程序,但我遇到了一些问题。我有一个带有按钮的 Activity,它以通常的方式替换片段:

public void onClick(View v) {
    final FragmentTransaction t = getFragmentManager().beginTransaction();
    t.setCustomAnimations(R.animator.fragment_slide_in_up, 0);
    t.replace(R.id.fragment_container,
        LogInFragment.newInstance(), LogInFragment.TAG)
        .addToBackStack(LogInFragment.TAG);
    t.commit();
}

在我的测试中,我点击发送新片段的按钮,然后检查新片段是否可见。

onView(withId(R.id.login_btn))
    .perform(click());
Thread.sleep(500);
onView(withId(R.id.email_input))
    .check(matches(isDisplayed()));

如果我从测试中删除 Thread.sleep(),即使我从 Activity 代码中删除 setCustomAnimations(),测试也会失败。

我的 phone 上的所有动画都已按照说明关闭。我的理解是 Espresso 知道 UI 线程状态并且会等到一切准备就绪。但是如果我做 onView(withId(R.id.widgetOnNewFragment)) 它每次都会爆炸。每次显示新片段时,我都需要添加一个 Thread.sleep(500)

我错过了什么吗?我想我不应该在我的测试代码中添加几十个 Thread.sleep()。

虽然 Espresso 框架 'waits' 用于某些主要 UI 线程活动,但动画需要 IdlingResource 方法(正如 Honza 所建议的)。

good tutorials on this concept, even detailed implementations.

实际上,由于动画很少影响 UI 的功能测试,因此大多数开发人员都禁用动画。 IMO,这是一个 anti-pattern because it doesn't map to the real user experience (most people buy a phone and use it with default settings). This is a decision you'll have to make yourself. If you want to include animations as part of your functional requirements, there are ways,但它需要您重新实现和重写您的测试。