Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

android - Robolectric buildActivity() with Mockito spy?

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.

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.

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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

I test it by Robolectric 3.1, and it's ok.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...