Gal*_*aim 6 java junit android android-testing
我是Android测试的新手,我想测试一个IntentService,我现在正在扩展ServiceTestCase.
我正在尝试使用a ResultReceiver但问题是OnReceiveResult在测试用例中从未调用过.(我也尝试创建ResultReceiverwith new Handler()作为参数insetad null但具有相同的结果.
我究竟做错了什么?什么是测试的正确方法IntentService?
这是服务:
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
public MyService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
final int action = intent.getIntExtra("action", 0);
final int request = intent.getIntExtra("request", 0);
final ResultReceiver receiver = (ResultReceiver) intent.getExtras().get("receiver");
if (receiver == null) {
return;
}
if (action == 0 || request == 0) {
receiver.send(0, null);
return;
}
}
Run Code Online (Sandbox Code Playgroud)
}
这是测试:
public void testHandleInvalidRequests() {
ResultReceiver receiver = new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
fail();
}
};
Intent intent = new Intent(mContext, MyService.class);
intent.putExtra("receiver", receiver);
startService(intent);
}
Run Code Online (Sandbox Code Playgroud)
我成功地测试了我的测试IntentService,我将在概念上向您展示我是如何做到的。
首先,扩展 Android 服务测试类:ServiceTestCase<MyIntentService>。然后你基本上就像IntentService使用 一样开始startService(intent)。
由于被测试的服务是一个IntentService,它将在生成的工作线程中完成所有工作。如果您不阻止测试线程,那么您的测试方法将立即执行断言,这显然会失败,因为后台的测试工作可能尚未完成。最终,测试方法将返回,并且您的测试将失败。
您需要做的是在之后阻塞您的测试线程startService。使用 aReentrantLock和调用它的 Condition来执行此操作await()。
then在后台IntentService执行。onHandleIntent我建议您扩展您的IntentService并覆盖onHandleIntent,然后调用super.onHandleIntent(),然后向您的测试线程发出信号表明工作已完成。在用于阻塞测试线程的相同锁和条件上执行此操作。
| 归档时间: |
|
| 查看次数: |
3610 次 |
| 最近记录: |