How to grant permissions to android instrumented tests?

拟墨画扇 提交于 2020-08-02 06:16:15

问题


I have an application that reads SMSs. The app works fine when debugging but when testing it using android instrumented test it throws the following error

java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider

This is my test case

@RunWith(AndroidJUnit4.class)
public class SmsFetcherTest {

   @Test
   public void fetchTenSms() throws Exception {
      // Context of the app under test.
      Context appContext = InstrumentationRegistry.getContext();

      //   Fails anyway.
      //   assertTrue(ContextCompat.checkSelfPermission(appContext,
      //     "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED);

      List<Sms> tenSms = new SmsFetcher(appContext)
              .limit(10)
              .get();

      assertEquals(10, tenSms.size());
   }
}

I'm new to instrumented tests. Is this is proper way to do this?

Or am I missing something?


回答1:


Use GrantPermissionRule. Here's how:

Add the following dependency to app/build.gradle:

dependencies {
    ...
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
}

Now add the following to your InstrumentedTest class:

import androidx.test.rule.GrantPermissionRule;

public class InstrumentedTest {
    @Rule
    public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
    ...
}



回答2:


You can grant the permission as follows:

@RunWith(AndroidJUnit4.class)
public class MyInstrumentationTest {
    @Rule
    public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
    ...

}


来源:https://stackoverflow.com/questions/50403128/how-to-grant-permissions-to-android-instrumented-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!