Baker
Baker

Reputation: 28060

Test Activity started from Service

Is it possible to test an Activity was started from an IntentService?

YourService svc = Robolectric.buildService(YourService.class).get();

Intent fakeIntent = new Intent();
svc.onHandleIntent(fakeIntent);

Service onHandleIntent() starts an activity.

How can we find and check that activity?

Notes

Upvotes: 1

Views: 85

Answers (1)

Baker
Baker

Reputation: 28060

YourService svc = Robolectric.buildService(YourService.class).get();

Intent fakeIntent = new Intent();
svc.onHandleIntent(fakeIntent);

ShadowService shSvc = shadowOf(svc);
Intent svcStartedIntent = shSvc.getNextStartedActivity();
ShadowIntent shIntent = shadowOf(svcStartedIntent);
assertThat(shIntent.getIntentClass()).isEqualTo(YourActivity.class);

As a generic method

public <ServiceType extends Service> boolean activityWasStartedFromService(Class actClass, Class<ServiceType> svClass) {
    ServiceType svc = Robolectric.buildService(svClass).get();

    ShadowService shSvc = shadowOf(svc);
    Intent svcStartedIntent = shSvc.getNextStartedActivity();
    if (svcStartedIntent == null) {
        return false;
    }

    ShadowIntent shIntent = shadowOf(svcStartedIntent);
    return shIntent.getIntentClass() == actClass;
}

Then to use

boolean activityStarted = activityWasStartedFromService(YourStartedActivity.class, YourService.class);
assertThat(activityStarted).isTrue();

Keep in mind that Robolectric's getNextStartedActivity() will consume the next activity. If you run this twice and 1st run was true, the 2nd run will return false.

Upvotes: 1

Related Questions