gpt4 book ai didi

使用 Espresso IdlingResource 进行 Android 测试

转载 作者:太空狗 更新时间:2023-10-29 14:48:16 26 4
gpt4 key购买 nike

我正在尝试测试 AutoCompleteTextView 是否会在键入某些单词后显示项目。但是在键入和显示弹出窗口之间存在延迟。首先,我使用的是 Thread.sleep(),它工作得很好。但我知道这种方法并不明确,所以我试图用 IdlingResource 来完成它。但这对我不起作用。我确实阅读了 Google 回复的前 5 页,但要么我不明白它应该如何工作,要么我的代码中有一些错误。

代码如下:

static class AutocompleteShowIdlingResource implements IdlingResource {

private Activity activity;
private @IdRes int resId;
private ResourceCallback resourceCallback;

public AutocompleteShowIdlingResource(Activity activity, @IdRes int resId) {
this.activity = activity;
this.resId = resId;
}

@Override
public String getName() {
return this.getClass().getName() + resId;
}

@Override
public boolean isIdleNow() {
boolean idle = ((AutoCompleteTextView) activity.findViewById(resId)).getAdapter() != null;
Log.d(TAG, "isIdleNow: " + idle);
if (idle) {
resourceCallback.onTransitionToIdle();
}
return idle;
}

@Override
public void registerIdleTransitionCallback(ResourceCallback callback) {
this.resourceCallback = callback;

}
}

测试本身:

    Activity activity = calibrationActivityRule.getActivity();
onView(withId(R.id.autocomplete_occupation)).perform(typeText("dok"));
IdlingResource idlingResource = new AutocompleteShowIdlingResource(activity, R.id.autocomplete_occupation);
Espresso.registerIdlingResources(idlingResource);
assertEquals(((AutoCompleteTextView) activity.findViewById(R.id.autocomplete_occupation)).getAdapter().getCount(), 3);
Espresso.unregisterIdlingResources(idlingResource);

但是当尝试在空适配器上调用 getCount() 时,测试在 java.lang.NullPointerException 上失败。正在打印日志

isIdleNow: false

就一次,这很奇怪。

关于如何使用 IdlingResource 的示例并不多,所以也许有人可以帮我说清楚。谢谢。

最佳答案

您的 IdlingResource 只有在与 onView(...).check(...) 或 onData(...).check(...) 一起使用时才会生效。实际上,“魔法”将在检查调用中发生——这是 Espresso 等待的地方,直到没有正在运行的 AsyncTasks 或没有阻塞的 IdlingResources。

现在让我们更正您的代码以使其正常工作:

Activity activity = calibrationActivityRule.getActivity();
onView(withId(R.id.autocomplete_occupation)).perform(typeText("dok"));
IdlingResource idlingResource = new AutocompleteShowIdlingResource(activity, R.id.autocomplete_occupation);

try {
Espresso.registerIdlingResources(idlingResource);

//that's where Espresso will wait until the idling resource is idle
onData(anything()).inAdapter(withId(R.id.autocomplete_occupation)).check(matches(isDisplayed());
finally {
Espresso.unregisterIdlingResources(idlingResource);
}
assertEquals(((AutoCompleteTextView) activity.findViewById(R.id.autocomplete_occupation)).getAdapter().getCount(), 3);

关于使用 Espresso IdlingResource 进行 Android 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37614214/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com