我想学习Robolectric,将其用于Android棉花糖应用程序的单元测试。我用一些方法编写了一个PermissionHelper
来简化权限处理。为了开始这个类的单元测试,我尝试测试最简单的方法:
public static boolean hasPermissions(Activity activity, String[] permissions) {
for (String permission : permissions) {
int status = ActivityCompat.checkSelfPermission(activity, permission);
if (status == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}
这是我到目前为止写的机器人分子测试:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class)
public class PermissionHelperTest {
private PermissionHelper permissionHelper;
private ShadowApplication application;
@Before
public void setup() {
PictureActivity activity = Robolectric.buildActivity(PictureActivity.class).get();
permissionHelper = new PermissionHelper(activity, activity, 1);
application = new ShadowApplication();
}
@Test
public void testHasPermission() throws Exception {
String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE};
boolean hasPermissions = permissionHelper.hasPermissions(permissions);
Assert.assertEquals(false, hasPermissions);
application.grantPermissions(permissions);
hasPermissions = permissionHelper.hasPermissions(permissions);
Assert.assertEquals(true, hasPermissions);
}
}
第一个断言有效(未授予许可)。但是,在通过shadowapplication授予所有权限之后,它们在下一个断言中仍然被拒绝。
我认为用
PictureActivity
创建的Robolectric.buildActivity()
没有使用shadowapplication进行权限检查。但是PictureActivity.getApplication()
没有给我一个ShadowApplication
来调用grantPermissions
的。我怎么测试这个?我对Android上的Robolectric和单元测试还不太熟悉……所以如果有其他的框架可以让这变得更容易/更可能的话:我愿意征求意见。
最佳答案
从Robolectric 4.2可以使用:
Application application = ApplicationProvider.getApplicationContext();
ShadowApplication app = Shadows.shadowOf(application);
app.grantPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE);