问题
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