2

In this question some years ago someone suggested unit-testing a startService call by using a specific Context.

Now, about 4 years later, I am wondering if this functionality can't be handled by some Framework like Espresso.

I have an intentservice:

public class MyService extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
        if (/* condition */) {
            /* do Something short-lasting */
        }
        return;
    }

My code starts a service in onCreate()

public class ListActivity extends SomeActivityClass {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startService(new Intent(this, MyService.class));
}

My testcode expects the service to be started:

@RunWith(AndroidJUnit4.class)
public class ListActivityTest {

    @Rule
    public final ActivityTestRule<ListActivity> rule 
        = new ActivityTestRule<ListActivity>(ListActivity.class, true, false);

    @Test
    public void test_startService() {
        Intents.init();

        Context targetContext = InstrumentationRegistry.getTargetContext();
        Intent showListIntent = new Intent(targetContext, ListActivity.class);
        rule.launchActivity(showListIntent);

        Intents.intended(IntentMatchers.hasComponent(MyService.class.getName()));

        Intents.release();
    }
}

My problem is, that it seems that the launch of the ListActivity is done but the framework does not wait for the intent to start the service to be issued.

I've tried to use an IdlingResource, but that means that i would have to add test code to production code, which i don't want to do, obviously: The IntentService i want to start is a short running piece of code, so recording some state about wether the IntentService is running or has ended already to return it to the IdlingResource callback is not an option.

Any hints how to check the startService call?

EDIT

Well, it seems that Robolectric can achieve exactly what i wanted using shadows.

Community
  • 1
  • 1
Bondax
  • 3,143
  • 28
  • 35
  • you can check by adding a log `@Test public void test_startService() { Intents.init(); Context targetContext = InstrumentationRegistry.getTargetContext(); Intent showListIntent = new Intent(targetContext, ListActivity.class); rule.launchActivity(showListIntent); **Log.w("service","called");** Intents.intended(IntentMatchers.hasComponent(MyService.class.getName())); Intents.release(); }` – SaravInfern Jun 06 '16 at 09:18
  • @SaravInfern Well i need an unittest or an integrationtest. – Bondax Jun 06 '16 at 09:20
  • @SaravInfern espresso-intents doesn't record intents started with `startService()`. – ashu Dec 03 '20 at 09:19

0 Answers0