我正在测试我的代码中调用Activity.requestPermissions()的方法。我想使用Robolectric阴影功能,所以我使用以下方法创建带有Robolectric的Activity
val mockActivity = Robolectric.setupActivity(AppCompatActivity::class.java)
但是我希望阴影活动可以在requestPermissions()调用上触发通用答案。
如果可以使用Robolectric阴影的Activity
作为Mockito的模拟,我可以做类似的事情:
@Test
fun testRequestPermissions()
{
val myCallback = MyCallback()
val mockActivity = Robolectric.setupActivity(AppCompatActivity::class.java)
val shadowActivity = shadowOf(mockActivity)
shadowActivity.grantPermissions(Manifest.permission.RECORD_AUDIO)
`when`(
mockActivity.requestPermissions(
eq(arrayOf(Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_FINE_LOCATION)), anyInt())).then {
myCallback.notify(
arrayOf(Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_FINE_LOCATION), intArrayOf(
PERMISSION_GRANTED, PERMISSION_GRANTED))
...
}
}
class MyCallback
{
fun notify(arrayOf: Array<String>, intArrayOf: IntArray){...}
}
但是无法在Robolectric Activity
上使用Mockito对方法进行存根。 Robolectric是否提供方法存根之类的东西?
不幸的是,我不能在这里使用任何自定义阴影。我尝试这样做:
@Implements(AppCompatActivity::class)
class ShadowAppCompatActivity() : ShadowActivity()
{
@Implementation
override fun requestPermissions(permissions: Array<out String>, requestCode: Int)
{
super.requestPermissions(permissions, requestCode)
myCallback.notify(permissions, requestCode)
}
}
但是requestPermissions()在ShadowActivity
中是最终的。
答案 0 :(得分:0)
ShadowActivity shadowActivity = Shadows.shadowOf(violationsActivity);
ShadowApplication application = Shadows.shadowOf(fragment.getActivity().getApplication());
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
application.grantPermissions(permissions);
ShadowActivity.PermissionsRequest permissionRequest= shadowActivity.getLastRequestedPermission();
assertEquals(1,permissionRequest.requestCode);
此代码将帮助我测试Activitiy.requestPermission(),您还可以使用活动代替应用程序