在我看来,使用 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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!