2

使用 robolectric 3.3,我试图让包管理器为 queryIntentServices 返回正确的值,以便 Firebase Job Dispatcher 工作。

在我的 AndroidManifest.xml 我有:

<service
    android:name="com.jongla.soundmash.service.SoundMashService"
    android:exported="false">
    <intent-filter>
      <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
    </intent-filter>
</service>

在 Robolectric 调用的测试应用程序类中,我放了:

val executeIntent = Intent("com.firebase.jobdispatcher.ACTION_EXECUTE")
executeIntent.setClassName(RuntimeEnvironment.application, "com.jongla.soundmash.service.SoundMashService")
Shadows.shadowOf(packageManager)
  .addResolveInfoForIntent(executeIntent, ResolveInfo().apply { serviceInfo = ServiceInfo().apply { enabled = true } })

但是,Firebase 仍然抛出此错误:

com.firebase.jobdispatcher.ValidationEnforcer$ValidationException: JobParameters is invalid: Couldn't find a registered service with the name
com.jongla.soundmash.service.SoundMashService. Is it declared in the manifest with the right intent-filter?

Firebase 项目中的相关代码如下。它看起来非常简单,所以我认为这不是他们这边的错误。

PackageManager pm = context.getPackageManager();
if (pm == null) {
    return getMutableSingletonList("PackageManager is null, can't validate service");
}

final String msg = "Couldn't find a registered service with the name " + service
    + ". Is it declared in the manifest with the right intent-filter?";

Intent executeIntent = new Intent(JobService.ACTION_EXECUTE);
executeIntent.setClassName(context, service);
List<ResolveInfo> intentServices = pm.queryIntentServices(executeIntent, 0);
if (intentServices == null || intentServices.isEmpty()) {
    return getMutableSingletonList(msg);
}

for (ResolveInfo info : intentServices) {
    if (info.serviceInfo != null && info.serviceInfo.enabled) {
// found a match!
return null;
    }
}

我在使用 Robolectric 时做错了什么?

4

1 回答 1

2

回答我自己的问题......调用代码需要在onCreate不是 beforeTest- 然后它工作得很好!

于 2017-06-19T19:15:37.613 回答