How can I shadow the PackageManager with Robolectric

后端 未结 6 837
有刺的猬
有刺的猬 2020-12-15 22:16

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( getStrin         


        
6条回答
  •  猫巷女王i
    2020-12-15 23:15

    You can set the ShadowPackageManager in a separate method (without extending RobolectricTestRunner)

    private void setupPackageManager() {
        ShadowApplication shadowApplication = shadowOf(Robolectric.application);
        shadowApplication.setPackageManager(mockPackageManager);
        List activities = new ArrayList();
        activities.add(resolveInfo("com.test.package.Class1"));
        activities.add(resolveInfo("com.test.package.Class2"));
        when(mockPackageManager.queryIntentActivities(any(Intent.class), anyInt())).thenReturn(activities);
    }
    

    Note : Here, i have used mockito & mocked the packagemanager for my unittest instead of using the actual PackageManager.

提交回复
热议问题