如何在Robolectric 3.4.2中模拟packageManager.queryIntentActivities?

时间:2017-09-11 11:07:36

标签: android robolectric

我有:

PackageManager packageManager = androidContext.getApplicationContext().getPackageManager();
final List appList = packageManager.queryIntentActivities(createIntentToLauncherActivity(), 0);

private Intent createIntentToLauncherActivity() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
return intent;
}

在源代码中,我可以模拟packageManager,但我在packageManager.queryIntentActivities(createIntentToLauncherActivity(), 0);获得例外。

我正在获取空的applist,但我需要设置像

这样的详细信息
log.d("Package Name: " + appInfo.activityInfo.packageName);
log.d("Activity Name: " + appInfo.activityInfo.name);
log.d("Process Name: " + appInfo.activityInfo.processName);

我用过

List appList = new ArrayList();    
ResolveInfo resolveInfo = new ResolveInfo();
resolveInfo.isDefault = true;
ActivityInfo activityInfo = new ActivityInfo();
activityInfo.packageName = "jp.co.ricoh.advop.simplecopy";
resolveInfo.activityInfo = new ActivityInfo();
resolveInfo.activityInfo = activityInfo;
resolveInfo.activityInfo.name = "Example";
appList.add(resolveInfo);

当我添加如下所示的条件来模拟queryIntentActivities时,如下所示:

when(shadowApplicationPackageManager.queryIntentActivities(createIntentToLauncherActivity(), 0)).thenReturn(appList);

After setting this I am getting

java.lang.reflect.InvocationTargetException
    org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
    ArrayList cannot be returned by toString()`enter code here`
    toString() should return String

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

首先,你必须决定你的测试是 Robolectric ,而不是嘲笑PackageManager,否则它将是JVM,你用 Mockito 来模拟它。 / p>

如果你选择 Robolectric ,那么你只需要指示ShadowPackageManager

PackageManager pm = RuntimeEnvironment.applicaition.getPackageManager();
ShadowPackageManager spm = shadowOf(pm);
spm.addResolveInfoForIntent(intent, list);

不幸的是,提供的部分代码并未显示您收到错误的确切位置。

由于运行时间的原因,我还建议避免使用Robolectric。