Android Robolectric unit test for Marshmallow PermissionHelper
From Robolectric 4.2 you can use:
Application application = ApplicationProvider.getApplicationContext();
ShadowApplication app = Shadows.shadowOf(application);
app.grantPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE);
Instead of using ActivityCompat
I'm using ContextCompat.checkSelfPermission()
which receives a context, so send a mock of the context and return permission granted, this is work for us:
Instead of:
ActivityCompat.checkSelfPermission(activity, permission);
use
ContextCompat.checkSelfPermission(context, permission);
then in your text you can send a mock directly to your hasPermissions
method and stub the result as:
Context context = mock(Context.class);
when(context.checkPermission(eq("YOUR_PERMISSION"),anyInt(),anyInt())).thenReturn(
PackageManager.PERMISSION_GRANTED);
Your problem is that you're using a different application to grant permissions, not your own.
Instead of this:
application = new ShadowApplication();
you should get a shadow of your application, like this:
application = Shadows.shadowOf(activity.getApplication());