使用Espresso IdlingResource进行Android测试

时间:2016-06-03 12:18:08

标签: android testing android-espresso

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

以下是代码:

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);

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

isIdleNow: false
只有一次,这很奇怪。

没有太多明显的例子如何使用IdlingResource,所以也许有人可以为我说清楚。感谢。

1 个答案:

答案 0 :(得分:0)

只有与onView(...)。check(...)或onData(...)一起使用时,你的IdlingResource才有效。检查(...)。实际上,“魔术”将在支票调用中发生 - 它是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);