使用Espresso IdlingResource进行Android测试

4
我正在测试AutoCompleteTextView是否在输入一些单词后显示项目。但是,输入和显示提示之间存在延迟。我最初使用Thread.sleep(),它运作良好。但我知道这种方法并不清晰,所以我正在尝试使用IdlingResource来实现。但对我而言它不起作用。我已经阅读了谷歌前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并没有太多清晰的例子,希望有人能为我澄清。谢谢。


请展示一下您是如何获取“activity”的。 - user35603
修改了我的问题。 - Georgiy Shur
1个回答

0

只有在与onView(...).check(...)或onData(...).check(...)一起使用时,您的IdlingResource才会产生影响。实际上,“魔法”将发生在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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接