Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Espresso with AsyncTask

I'm trying to write a test for my SignIn Activity, in which I'm using an AsyncTask.

public class SignInActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {

    .........

    new AsyncSignButton().execute();
}

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

For testing, I have tried using IdlingResource, but I do not understand how would use it with an AsyncTask, not with a WebView as in the examples, just simple a AsyncTask.


Here is my Test code:

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

}
like image 579
Drake Avatar asked Jan 02 '15 19:01

Drake


People also ask

What are the problems in AsyncTask in Android?

In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.

How do you implement AsyncTask?

To start an AsyncTask the following snippet must be present in the MainActivity class : MyTask myTask = new MyTask(); myTask. execute(); In the above snippet we've used a sample classname that extends AsyncTask and execute method is used to start the background thread.

How many times an instance of AsyncTask can be executed?

AsyncTask instances can only be used one time.


1 Answers

Good news, you don't need any custom IdlingResource for AsyncTask: Espresso already waits for all tasks to have run before executing actions/assertions. This is mentioned for example here.

like image 170
Gil Vegliach Avatar answered Oct 15 '22 03:10

Gil Vegliach