I’m wondering how should i ask for permissions at runtime using the MVP architecture (so i can unit test it).
@szczurk3y Do you still have issues with this?
I’m developing an android app in which I have to ask for permissions at runtime. I’m wondering about the best way to implement that using Model-View-Presenter architecture.
My initial thought was to have the presenter call a component responsible for permissions(say a PermissionHandler), and update view accordingly.
The issue is that the code to check for permissions is tightly coupled with the Activity class. Here are some of the methods involved that require an Activity or Context:
ContextCompat.checkSelfPermission()
ActivityCompat.shouldShowRequestPermissionRationale()
ActivityCompat.requestPermissions()
onRequestPermissionsResult()(callback)
This means I would have to pass an activity object to the presenter, which I didn’t like much because I’ve heard that keeping your presenter free from Android code is good for testing.
Due to that, I then thought about handling permissions at view level(in an activity), but then I guess this would hurt the purpose of leaving the view responsible only for UI updates, without business logic.
To ask for runtime permissions in MVP for unit testing, create a PermissionView
interface with methods like requestPermissions
, showPermissionRationale
, onPermissionsGranted
, and onPermissionsDenied
. Your Activity/Fragment implements this interface to handle actual Android permission requests. Your Presenter holds the permission logic and interacts with the PermissionView
interface. For testing, mock the PermissionView
in your Presenter unit tests to verify the permission request flow without Android dependencies. This separation of concerns ensures testability.