I am writing a very simple unit test case for my Android project, the test script just executes AsyncTask, which performs a network operation in the background. I am extending the class AndroidTestCasefor my test case:
public class MyTest extends AndroidTestCase{
private CountDownLatch signal;
@Override
public void setUp() throws Exception{
super.setUp();
signal = new CountDownLatch(1);
}
@Override
public void runTest() throws Exception{
String params = "some params";
new MyAsyncTask().execute(params);
try {
signal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class MyAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.i("Debug","post execute");
signal.countDown();
}
}
}
As you see above, I use CountDownLatch to execute the wait-notify behavior .
After starting MyAsicTaskI call signal.await()to wait for MyAsyncTaskto the completion.
In onPostExecute()the callback, MyAsyncTaskI call signal.countDown()in to notify that the task is completed.
, onPostExecute , ?
======== ==========
Thread.sleep(30*1000) runTest(), . , teardown() . tearDown(), Android. .
, wait-notify CountDownLatch ... ?