Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

android - How can I shadow the PackageManager with Robolectric

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();
    }
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...