棉花糖PermissionHelper的Android Robolectric单元测试 [英] Android Robolectric unit test for Marshmallow PermissionHelper
问题描述
我想学习Robolectric,将其用于Android Marshmallow应用程序上的单元测试.我用一些方法编写了PermissionHelper
,使权限处理更加容易.为了开始使用此类的单元测试,我正在尝试测试最简单的方法:
I wanna learn Robolectric to use it for unit tests on an Android Marshmallow app. I wrote a PermissionHelper
with some methods to make permission handling a bit easier. To get started with unit tests for this class, I am trying to test the most simple method:
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;
}
这是我到目前为止编写的Robolectric测试:
Here is the Robolectric test that I wrote so far:
@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授予所有权限之后,它们仍将在下一个断言中被拒绝.
The first Assert works (no permission granted). But after granting all permissions via the ShadowApplication they are still denied in the next Assert.
我认为用Robolectric.buildActivity()
创建的PictureActivity
没有使用ShadowApplication进行权限检查.但是PictureActivity.getApplication()
并没有给我ShadowApplication
来调用grantPermissions
.我该如何测试?
I think that the PictureActivity
created with Robolectric.buildActivity()
is not using the ShadowApplication for the permission checks. But PictureActivity.getApplication()
does not give me a ShadowApplication
to call grantPermissions
on. How can I test this?
我是Robolectric和Android上的单元测试的新手...因此,如果有其他框架可以使此操作变得容易/可行:我愿意征求建议.
I am new to Robolectric and unit testing on Android...so if there is any other framework that makes this easier/possible: I am open for suggestions.
推荐答案
在Robolectric 4.2中,您可以使用:
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);
这篇关于棉花糖PermissionHelper的Android Robolectric单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!