how to JUnit test IntentService

android, android-testing, java, junit

Solution

I successfully managed to test my `IntentService` and I will show you conceptually how I did it.

First, you extend the Android Service Testing class: `ServiceTestCase<MyIntentService>`. Then you basically start the `IntentService` as you did using `startService(intent)`.

Since the service under test is an `IntentService`, it will do all work in a spawned worker thread. If you do not block your test thread then your test method will immediately do assertions that will obviously fail since the test work in the background has probably not finished yet. Eventually, the test method will return and your test will fail.

What you need to do is to block your test thread after `startService`. Do this using a `ReentrantLock` and a Condition calling `await()` on it.

The `IntentService` then executes `onHandleIntent` in the background. I suggest you extend your `IntentService` and override `onHandleIntent`, calling `super.onHandleIntent()` and after that, signal your test thread that the work has been done. Do this on the same lock and condition used for blocking the testing thread.

Problem

I'm new into Android testing, I want to test an IntentService and I'm currently extending ServiceTestCase. I'm trying to use a `ResultReceiver` but the problem is that `OnReceiveResult` is never called within the test case. (I also tried creating the `ResultReceiver` with `new Handler()` as the argument insetad of `null` but with the same result. what am I doing wrong? what is the proper way to test an `IntentService` ? this is the service: ``` 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; } } ``` } and this is the test: ``` 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); } ```

Original source

Related problems