无法解析方法getIdlingResource() - Android Espresso

时间:2017-08-28 21:49:27

标签: android android-espresso

我尝试在网络调用完成后尝试使用IdlingResources进行测试。我有CountingIdlingResource跟踪我的主要活动中正在运行的作业,但我的测试文件无法识别getIdlingResource

enter image description here

以下是我的导入声明:

package com.example.android.bakingapp;

import android.support.test.espresso.Espresso;
import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

import com.example.android.bakingapp.activities.MainActivity;
import com.example.android.bakingapp.activities.RecipeActivity;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.intent.Intents.intended;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.matcher.ViewMatchers.withId;

我也有这个包含在我的gradle依赖项中:

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
compile 'com.android.support.test.espresso:espresso-idling-resource:2.2.2'

3 个答案:

答案 0 :(得分:5)

您是否将此依赖项添加到gradle?

androidTestCompile' com.android.support.test.espresso:espresso-core:2.2.2'

编译' com.android.support.test.espresso:espresso-idling-resource:2.2.2'

答案 1 :(得分:3)

首先,您必须在MainActivity中创建 getIdlingResource()方法:

@Nullable
private SimpleIdlingResource mIdlingResource;

@VisibleForTesting
@NonNull
public IdlingResource getIdlingResource() {
    if (mIdlingResource == null) {
        mIdlingResource = new SimpleIdlingResource();
    }
    return mIdlingResource;
}

,然后创建一个空闲资源类:

public class SimpleIdlingResource implements IdlingResource {

    @Nullable private volatile ResourceCallback mCallback;

    private AtomicBoolean mIsIdleNow = new AtomicBoolean(true);

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

    @Override
    public boolean isIdleNow() {
        return mIsIdleNow.get();
    }

    @Override
    public void registerIdleTransitionCallback(ResourceCallback callback) {
        mCallback = callback;
    }

    public void setIdleState(boolean isIdleNow) {
        mIsIdleNow.set(isIdleNow);
        if (isIdleNow && mCallback != null) {
            mCallback.onTransitionToIdle();
        }
    }
}

答案 2 :(得分:0)

您需要在Activity类中添加该方法。这是来自google示例的示例项目。

https://github.com/googlesamples/android-testing/tree/master/ui/espresso/IdlingResourceSample