我正在爲使用ServiceTestCase的服務編寫單元測試。AsyncTask.onPostExecute()永遠不會在ServiceTestCase中調用
該服務基本上執行一個AsyncTask,它執行一些工作,然後在onPostExecute()中執行其他操作。
當我在(虛擬)設備上運行和調試時,該服務按預期工作。
但是在擴展ServiceTestCase的測試中,我只能進入doInBackground()。一旦這些方法返回,onPostExecute()永遠不會被調用。我讓測試sleep(),以便AsyncTask有時間來完成它的工作。
這是簡化的服務:
public class ServiceToTest extends Service {
private AtomicBoolean busy = new AtomicBoolean(false);
@Override
public IBinder onBind(final Intent intent) {
return null;
}
@Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
this.handleCommand();
return START_NOT_STICKY;
}
/**
* Workaround for http://code.google.com/p/android/issues/detail?id=12117
*/
@Override
public void onStart(final Intent intent, final int startId) {
this.handleCommand();
}
public void handleCommand() {
new TaskToTest().execute();
}
public boolean isBusy() {
return busy.get();
}
private class TaskToTest extends AsyncTask<Boolean, Void, TestInfo> {
@Override
protected void onPreExecute() {
busy.set(true);
}
@Override
protected TestInfo doInBackground(final Boolean... args) {
return null;
}
@Override
protected void onPostExecute(final TestInfo info) {
busy.set(false);
}
}
}
的,這是因爲它的測試:
public class ServiceTest extends ServiceTestCase<ServiceToTest> {
public ServiceTest() {
super(ServiceToTest.class);
}
public void testIsBusy() throws InterruptedException {
startService(new Intent("this.is.the.ServiceToTest"));
ServiceToTest serviceToTest = this.getService();
assertTrue(serviceToTest.isBusy());
Thread.sleep(10000);
assertFalse(serviceToTest.isBusy());
}
}
我假定由ServiceTestCase提供的環境是比較有限所以這並未不工作,但有什麼我可以做的,無論如何使它工作?
乾杯, 託斯滕
請張貼代碼... – neteinstein 2011-05-19 22:11:50
你檢查,如果你從DoInBackground返回一個非空的結果會發生什麼? – Torid 2011-05-19 23:51:30
是的,我試過了,它沒有任何區別 – 2011-05-20 11:57:05