我正在为我的 Android 项目编写一个非常简单的单元测试用例,测试用例简单地执行一个在后台进行网络操作的 AsyncTask
。我正在为我的测试用例扩展 AndroidTestCase
类:
public class MyTest extends AndroidTestCase{
//use CountDownLatch to perform wait-notify behavior
private CountDownLatch signal;
@Override
public void setUp() throws Exception{
super.setUp();
//I use CountDownLatch to perform wait-notify behaviour
signal = new CountDownLatch(1);
}
@Override
public void runTest() throws Exception{
String params = "some params";
//MyAsyncTask does the networking tasks
new MyAsyncTask().execute(params);
//wait until MyAsyncTask is done
try {
signal.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private class MyAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
//Do networking task e.g. access a remote database
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
//this never get called when run this test case, why?
Log.i("Debug","post execute");
signal.countDown();
}
}
}
正如您在上面看到的,我使用的是 CountDownLatch执行等待通知行为。
MyAsicTask
启动后,我调用 signal.await()
来等待 MyAsyncTask
完成。
在 MyAsyncTask
的 onPostExecute()
回调中,我调用 signal.countDown()
来通知任务完成。
但是当我运行这个测试用例时,onPostExecute
从未被调用,为什么以及如何修复它?
========更新==========
在 runTest()
的最后一行添加 Thread.sleep(30*1000)
后,我可以看到更多来自网络操作的日志。它证明 teardown()
在我的网络操作完成之前被调用。我在 tearDown() 中什么也没做,android 测试框架。自动调用它。
似乎我使用 CountDownLatch
的wait-notify 不起作用...为什么?
最佳答案
因为我遇到了同样的问题...这就是为我解决的问题。 我没有让它扩展 AndroidTestCase,而是让它扩展了 InstrumentationTestCase。
然后我像这样启动 asyncTask:
runTestOnUiThread(new Runnable()
{
@Override
public void run()
{
startAsyncTask();
}
});
关于java - AndroidTestCase 中永远不会调用 AsyncTask 的 onPostExecute(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19635308/