我怎样才能影线的Robolectric的PackageManager [英] How can I shadow the PackageManager with Robolectric

查看:345
本文介绍了我怎样才能影线的Robolectric的PackageManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Andr​​oid应用程序有一个简单的方法来断火的意图显示的URL。

My Android application has a simple method to fire off an intent to display a URL.

protected void launchBrowser(int id)
{
    Uri uri = Uri.parse( getString( id ) );
    Intent intent = new Intent( ACTION_VIEW, uri);

    PackageManager packageManager = getPackageManager();
    List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
    if (activities.size() > 0)
    {
        startActivity(intent);
    }
    else
    {
        Toast.makeText(getApplicationContext(),
                       "ERROR - no application to display a web page",
                       Toast.LENGTH_SHORT).show();
    }
}

我使用Robolectric进行单元测试,但我无法验证此方法。具体而言, getPackageManager()总是返回null。我怎样才能影着 PackageManager ?我试图创建一个 ShadowPackageManager 并调用 bindShadowClass ,但没有我的code被执行 - getPackageManager()总是返回。我也试过要隐藏应用程序上下文,并返回一个具体的 StubPackageManager ,但得到了同样的结果。 也许我一直在寻找/盯着太久 - ?有没有更好的方式来进行单元测试这种方法

I'm using Robolectric for unit testing but I'm having trouble verifying this method. Specifically, getPackageManager() is always returning null. How I can shadow the PackageManager? I tried creating a ShadowPackageManager and calling bindShadowClass, but none of my code gets executed - getPackageManager() always returns null. I also tried to Shadow the Application context and return a concrete StubPackageManager, but got the same results. Maybe I've been searching/staring too long - is there a better way to unit test this method?

推荐答案

我使用Robolectric 2.3本。正如在其他的答案指出, getPackageManager()没有返回null,但 shadowApplication.setPackageManager 已不存在。

I'm using Robolectric 2.3 for this. As noted in other answers, getPackageManager() does not return null, but shadowApplication.setPackageManager no longer exists.

既然你不能嘲笑 PackageManager ,你不能给它意图的列表解析。幸运的是,Robolectric的 PackageManager 的子类, RobolectricPackageManager ,可以让你不用模拟添加这些意图:

Since you can't mock PackageManager, you can't give it a list of Intents to resolve for. Fortunately, Robolectric's PackageManager subclass, RobolectricPackageManager, can let you add these intents without a mock:

RobolectricPackageManager rpm = (RobolectricPackageManager)Robolectric.application.getPackageManager();
rpm.addResolveInfoForIntent(new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS), new ResolveInfo());

这篇关于我怎样才能影线的Robolectric的PackageManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆