How to grant permissions to android instrumented tests?
10,165
Solution 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);
...
}
Solution 2
You can grant the permission as follows:
@RunWith(AndroidJUnit4.class)
public class MyInstrumentationTest {
@Rule
public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
...
}
Author by
rsanath
Updated on June 24, 2022Comments
-
rsanath about 2 years
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?