Android espresso 对于测试用例非常有用。但是当我使用 IdlingResource
时出现了一些问题。
我的 Activity
中有一个标志,我会在每次初始完成时将其设置为 true
。
所以我的 IdlingResource 是这样的:
/**
* 等待所有初始化工作完成
*/
private class WaitPingSuccessIdlingResource implements IdlingResource {
private ChoiceServerActivity choiceServerActivity;
private ResourceCallback mResourceCallback;
public WaitPingSuccessIdlingResource(ChoiceServerActivity choiceServerActivity) {
this.choiceServerActivity = choiceServerActivity;
}
@Override
public String getName() {
return String.valueOf(hashCode());
}
@Override
public boolean isIdleNow() {
if (mResourceCallback != null && choiceServerActivity.isAllDataInited()) {
mResourceCallback.onTransitionToIdle();
}
boolean rst = choiceServerActivity.isAllDataInited();
Log.i("tonghu","WaitPingSuccessIdlingResource, isIdleNow(L94): rst " + rst);
return rst;
}
@Override
public void registerIdleTransitionCallback(ResourceCallback callback) {
this.mResourceCallback = callback;
}
}
然后我这样注册:
Espresso.registerIdlingResources(new WaitPingSuccessIdlingResource(activity));
Log.i("tonghu", "ChoiceServerActivityTest, testPingSuccess(L42): 2222");
通常情况下,只有当isIdleNow()
返回true
时,才会打印第二条日志。
但现在我的日志是:
I/tonghu (23470): WaitPingSuccessIdlingResource, isIdleNow(L94): rst false
I/tonghu (23470): ChoiceServerActivityTest, testPingSuccess(L42): 2222
为什么当我的 IdlingResource 不空闲时第二个日志可以打印。
我的英文很差,有什么问题请告诉我!谢谢!
已编辑: 我已经解决了这个问题:
我看到类 IdlingResource
上有一条评论:
In such cases, test authors can register the custom resource and
{@link Espresso} will wait for the resource to become idle prior
to executing a view operation.
所以在注册Idling资源后,给任意一个view action:
Espresso.registerIdlingResources(new WaitPingSuccessIdlingResource(activity));
Espresso.onView(ViewMatchers.withId(R.id.list_view)).check(ViewAssertions.matches(ViewMatchers.isDisplayed()));
最佳答案
同样的问题,发现注册idlingResources不会导致Espresso等待,但是除了Espresso.onView
,还可以使用Espresso.onIdle()
等待使已注册的 idlingResources 变为空闲状态。
终于找到了官方文档,引用自here :
Register idling resources before you need them.
The synchronization benefits associated with idling resources only take effect following Espresso's first invocation of that resource's isIdleNow() method.
The following list shows several examples of this property:
- If you register an idling resource in a method annotated with @Before, the idling resource takes effect in the first line of each test.
- If you register an idling resource inside a test, the idling resource takes effect during the next Espresso-based action. This behavior still occurs even if the next action is in the same test as the statement that registers the idling resource.
关于android - Espresso 空闲资源不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33120493/