是否可以测试从IntentService启动的活动?
YourService svc = Robolectric.buildService(YourService.class).get(); Intent fakeIntent = new Intent(); svc.onHandleIntent(fakeIntent);
服务onHandleIntent()
启动活动。
我们如何找到并检查该活动?
注释
答案 0 :(得分:1)
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);
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;
}
boolean activityStarted = activityWasStartedFromService(YourStartedActivity.class, YourService.class);
assertThat(activityStarted).isTrue();
请记住,Robolectric的getNextStartedActivity()
将消耗下一个活动。如果你运行两次并且第一次运行为true,则第二次运行将返回false。