問題描述
在我看來,使用 Robolectric 的生命周期實(shí)用程序(從 Robolectric.buildActivity()
開始)構(gòu)建 Activity 單元測試和使用 Mockito 間諜監(jiān)視同一個(gè) 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.
因?yàn)?code>buildActivity()控制了Activity對象的構(gòu)建,所以唯一給Activity添加spy的地方就是調(diào)用buildActivity()
之后.但是,在事后添加間諜時(shí),間諜無法正常工作.
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.
在監(jiān)視 ActivityController
生命周期方法的副作用時(shí)尤其如此,例如 create()
、start()
和 恢復(fù)()
.我認(rèn)為這是因?yàn)?ActivityController 持有對真實(shí)"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.
那么有什么方法可以監(jiān)視正在使用 Robolectric 進(jìn)行單元測試的 Activity,以便在通過 Robolectric 的 ActivityController
調(diào)用生命周期方法時(shí),間諜可以正常工作?
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
中真實(shí)的"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.
這篇關(guān)于帶有 Mockito 間諜的 Robolectric buildActivity()?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!