gpt4 book ai didi

android - AsyncTask.onPostExecute() 永远不会在 ServiceTestCase 中被调用

转载 作者:太空狗 更新时间:2023-10-29 13:40:45 24 4
gpt4 key购买 nike

我正在使用 ServiceTestCase 为服务编写单元测试。

该服务基本上执行一个 AsyncTask,该 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 提供的环境有些受限,所以这行不通,但我能做些什么来让它正常工作吗?

干杯,托尔斯滕

最佳答案

问题是你的后台线程正在等待 UI 被“激活”,你需要调用 Looper.prepare()Looper.loop() .在 this page 中有更好的解释.

关于android - AsyncTask.onPostExecute() 永远不会在 ServiceTestCase 中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6065351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com