Notes on Android Testing
Granting Permissions
JUnit5 apparently does not support
@Rule
: http://www.douevencode.com/articles/2018-06/grant-permission-no-rule/ “JUnit5, which is ultimately the future discourages to use@Rules
"JUnit5 has a planned feature to replace
GrantPermissionRule
but work on it seems to have stalled (as of this writing - 16 March 2022 - the feature has been part of the JUnit5 milestone “instrumentation-1.3.1” since 17 September 2021: https://github.com/mannodermaus/android-junit5/issues/251 )With the above said, we can hack in a workaround to be able to grant permissions:
import androidx.test.runner.permission.PermissionRequester; public class SomeClass { // Hacky workaround for JUnit5 not supporting @Rule private void GrantPermissions(String ... permissions) { PermissionRequester pr = new PermissionRequester(); pr.addPermissions(permissions); pr.requestPermissions(); } }
Usage:
public class SomeClass { //... @Test public void SomeExampleTest() { GrantPermissions(android.Manifest.permission.BLUETOOTH_SCAN); VictorBleDeviceManager dm = new VictorBleDeviceManager(ApplicationProvider.getApplicationContext()); List<VictorDeviceInfo> scannedDevices = dm.ScanForDevices().get(); assertTrue(scannedDevices.isEmpty()); } }