我刚开始使用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()
,测试也会失败。按照说明,我手机上所有的动画都已关闭。我的理解是Espresso知道UI线程状态,并且会等待一切准备就绪。但是,如果我执行
onView(withId(R.id.widgetOnNewFragment))
,它每次都会崩溃。我需要在显示新片段时每次都添加Thread.sleep(500)
。我是否漏掉了什么?我认为我的测试代码不应该添加数十个
Thread.sleep()
。
Fragment
和Activity
转换发生在主线程上,因此我们不需要实现任何IdlingResource
。 - pvd