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?
I upgraded to the latest Robolectric (version 2.1.1) and the PackageManager doesn't come up
null
anymore.The code below verifies that a browser intent is fired (and configured with a url). I haven't tested this on 1.x, but I think it works there too:
Note: I'm invoking start activity from a fragment here.
You can set the ShadowPackageManager in a separate method (without extending RobolectricTestRunner)
Note : Here, i have used mockito & mocked the packagemanager for my unittest instead of using the actual PackageManager.
For Robolectric 3.1 you can
I'm using Robolectric 2.3 for this. As noted in other answers,
getPackageManager()
does not return null, butshadowApplication.setPackageManager
no longer exists.Since you can't mock
PackageManager
, you can't give it a list ofIntents
to resolve for. Fortunately, Robolectric'sPackageManager
subclass,RobolectricPackageManager
, can let you add these intents without a mock:For some reason you need to set the shadow packagemanager manually on your application. Create a custom test runner (by extending RobolectricTestRunner) and override the setApplicationState method:
Then specify in your tests that you want to use your own test runner:
Just add on to aleph_null's answer, you can use
ShadowResolveInfo.newResolveInfo()
to quickly create a mockResolveInfo
ready to be used (I'm using Robolectric 2.4).