我是新的Android測試,我想測試一個IntentService,我目前正在擴展ServiceTestCase。如何JUnit測試IntentService
我試圖使用ResultReceiver
,但問題是OnReceiveResult
永遠不會在測試用例中調用。 (我也嘗試創建ResultReceiver
與new Handler()
作爲null
參數insetad,但具有相同的結果。
我究竟做錯了什麼? 什麼是測試一個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;
}
}
}
,這是測試:
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);
}
你能給這裏使用一個ReentrantLock的例子嗎? – 2015-01-29 23:22:41
我也會非常感興趣的例子(甚至兩年後)。謝謝。 – JDenais 2015-02-10 03:00:47
嗨,我用來初始化意圖的任何上下文似乎拋出一個空指針異常。你是如何設定你的環境的? – kyrax 2016-04-18 15:43:31