Espresso与AsyncTask

时间:2015-01-02 19:00:17

标签: android-testing android-espresso

我正在尝试为我的SignIn Activity编写一个测试,我正在使用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;
    }
}

}

1 个答案:

答案 0 :(得分:10)

好消息,AsyncTask不需要任何自定义IdlingResource:Espresso已经等待所有任务在执行操作/断言之前运行。例如here提到了这一点。