Robolectric buildActivity() with Mockito spy?(带有 Mockito 间谍的 Robolectric buildActivity()?)
问题描述
在我看来,使用 Robolectric 的生命周期实用程序(从 Robolectric.buildActivity() 开始)构建 Activity 单元测试和使用 Mockito 间谍监视同一个 Activity 是相互排斥的.
It seems to me that building an Activity unit test with Robolectric's lifecycle utilities (starting with Robolectric.buildActivity()) and spying on the same Activity with a Mockito spy are mutually exclusive.
因为buildActivity()控制了Activity对象的构建,所以唯一给Activity添加spy的地方就是调用buildActivity()之后.但是,在事后添加间谍时,间谍无法正常工作.
Because buildActivity() controls the construction of the Activity object, the only place to add a spy for the Activity is after calling buildActivity(). However, the spy doesn't function properly when it's added after the fact.
在监视 ActivityController 生命周期方法的副作用时尤其如此,例如 create()、start() 和 恢复().我认为这是因为 ActivityController 持有对真实"Activity 对象的引用,而不是后来添加的间谍.
This is especially true when spying for side effects of ActivityController lifecycle methods such as create(), start() and resume(). I assume this is because the ActivityController holds a reference to the "real" Activity object and not the spy that was added later.
那么有什么方法可以监视正在使用 Robolectric 进行单元测试的 Activity,以便在通过 Robolectric 的 ActivityController 调用生命周期方法时,间谍可以正常工作?
So is there any way to spy an Activity that's being unit tested with Robolectric, such that the spy works properly when calling the lifecycle methods via Robolectric's ActivityController?
推荐答案
答案是用反射替换ActivityController中真实的"Activity对象.p>
The answer is using the reflection to replace the "real" Activity object in ActivityController.
@Test
public void someTestMethod() throws NoSuchFieldException, IllegalAccessException {
ActivityController<LoginActivity> ac = Robolectric.buildActivity(LoginActivity.class);
LoginActivity spiedActivity = spy(ac.get());
replaceComponentInActivityController(ac, spiedActivity);
ac.create();
// do your work
}
public static void replaceComponentInActivityController(ActivityController<?> activityController, Activity activity)
throws NoSuchFieldException, IllegalAccessException {
Field componentField = ComponentController.class.getDeclaredField("component");
componentField.setAccessible(true);
componentField.set(activityController, activity);
}
我用Robolectric 3.1测试过,没问题.
I test it by Robolectric 3.1, and it's ok.
这篇关于带有 Mockito 间谍的 Robolectric buildActivity()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有 Mockito 间谍的 Robolectric buildActivity()?
基础教程推荐
- 通过重定向链接在 Google Play 中打开应用 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- iOS4 创建后台定时器 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
