How can I shadow the PackageManager with Robolectric

后端 未结 6 834
有刺的猬
有刺的猬 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条回答
  •  别那么骄傲
    2020-12-15 23:02

    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:

    public class MyTestRunner extends RobolectricTestRunner {   
      @Override
      public void setupApplicationstate(RobolectricConfig robolectricConfig) {
         super.setupApplicationState(robolectricConfig);
         ShadowApplication shadowApplication = shadowOf(Robolectric.application);
         shadowApplication.setPackageName(robolectricConfig.getPackageName());
         shadowApplication.setPackageManager(new RobolectricPackageManager(Robolectric.application, robolectricConfig));
      }
    }
    

    Then specify in your tests that you want to use your own test runner:

    @RunWith(MyTestRunner.class)
    public class MyTest { ... }
    

提交回复
热议问题