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?
Instrumented tests run on Android devices, whether physical or emulated. As such, they can take advantage of the Android framework APIs. Instrumented tests therefore provide more fidelity than local tests, though they run much more slowly.
To check if the user has already granted your app a particular permission, pass that permission into the ContextCompat. checkSelfPermission() method. This method returns either PERMISSION_GRANTED or PERMISSION_DENIED , depending on whether your app has the permission.
When you use AndroidJUnitRunner to run your tests, you can access the context for the app under test by calling the static ApplicationProvider. getApplicationContext() method. If you've created a custom subclass of Application in your app, this method returns your custom subclass's context.
Use GrantPermissionRule
. Here's how:
Add the following dependency to app/build.gradle
:
dependencies { ... androidTestImplementation 'androidx.test:rules:1.2.0' }
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); ... }
You can grant the permission as follows:
@RunWith(AndroidJUnit4.class) public class MyInstrumentationTest { @Rule public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS); ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With