带有 AsyncTask 的 Espresso

Espresso with AsyncTask

我正在尝试为我使用 AsyncTask 的登录活动编写测试。

public class SignInActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {

    .........

    new AsyncSignButton().execute();
}

class AsyncSignButton extends AsyncTask<Void, Void, Integer>{
   ....... 
}

为了测试,我尝试使用 IdlingResource,但我不明白如何将它与 AsyncTask 一起使用,而不是像示例中那样与 WebView 一起使用,只是简单的 AsyncTask。


这是我的测试代码:

public class Test extends ActivityInstrumentationTestCase2<SplashActivity> {

private SplashActivity mActivity;

public Test(){
    super(SplashActivity.class);
}

public Test(Class<SplashActivity> activityClass) {
    super(activityClass);
}

@Override
protected void setUp() throws Exception{
    super.setUp();
    mActivity = getActivity();
    //how call it?
}

@LargeTest
public void testList() throws InterruptedException {

   //wait AsyncTask before call
   onView(withId(R.id.action_bar_accept_button)).perform(click());

}

public final class AsyncIdlingResource implements IdlingResource {

    private AsyncTask asyncTask;
    private ResourceCallback callback;

    public AsyncIdlingResource(AsyncTask asyncTask){
        this.asyncTask = checkNotNull(asyncTask);
    }

    @Override
    public String getName() {
        return "Sign idling resource";
    }

    @Override
    public boolean isIdleNow() {
        if(asyncTask == null) return true;
        return asyncTask.getStatus() == AsyncTask.Status.FINISHED;
    }

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

}

好消息,AsyncTask 不需要任何自定义 IdlingResource:Espresso 在执行 actions/assertions 之前已经等待所有任务 运行。例如 here.