How to test a asyncTask
package com.udacity.gradle.builditbigger;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class testEndpointsAsyncTask extends ActivityInstrumentationTestCase2<MainActivity> {
public testEndpointsAsyncTask() {
super(MainActivity.class);
}
public void testtheEndpointsAsyncTask() throws Throwable {
final String[] testedResult = new String[1];
final CountDownLatch signal=new CountDownLatch(1);
final EndpointsAsyncTask task=new EndpointsAsyncTask(){
@Override
protected void onPostExecute(String result) {
// super.onPostExecute(result);
testedResult[0] =result;
signal.countDown();
}
};
runTestOnUiThread(new Runnable() {
@Override
public void run() {
// task.execute(getActivity());
}
});
task.execute(getActivity());
signal.await(30, TimeUnit.SECONDS);
assertFalse(testedResult[0].equals(""));
}
}
|
above code explain:
we have a task that will return the string after finish execute.
CountDownLatch is a timer,when call await,it will stop the thread,and wait unti the count is zeron or wait 30s.we need this timer because when we start the asyncTask ,it will execute on the other thread. However,the Junit test thread will not wait the asyncTask finish and test the result come from Junit test thread(get at onPostExecute).So when we start the asynctask by task.execute(getActivity()); we nedd to use signal.await(30, TimeUnit.SECONDS); to stop the Junit test class,when the asynctask finish ,it will call onPostExecute,this one should be run on the Junittest thread,not the asyncTask thread. signal.countDown(); call,so the Junittest thread run agian.so this is the time to do the Test!!