现有一个需求需要在Junit测试时动态申请权限,所以撰写一下相关笔记
AndroidManifest.xml 注册相关权限,这一步非常重要,否则也无法申请到权限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="top.foxhome.libiwb">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>
build.gradle添加相关类库
如果工程为androidx
dependencies {
...
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test:rules:1.1.0'//添加权限规则类
...
}
如果工程为support
dependencies {
...
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test:rules:1.0.2'//添加权限规则类
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
...
}
测试类使用代码
top.foxhome.libiwb.ExampleInstrumentedTest.java
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
//把需要申请的权限全部传递到grant里面去
@Rule
public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE);
@Test
public void useAppContext() throws IOException {
// Context of the app under test.
File file = new File("/sdcard/iwb.xml");
mXmlFile.delete();//经过上面的注册这里已经可以正常使用的读写权限了
}
}
不错,老铁,很实用!坚持写!