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;
}
}
}
In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.
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.
AsyncTask instances can only be used one time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With