Robolectric buildActivity() with Mockito spy?

后端 未结 2 1087
情话喂你
情话喂你 2020-12-20 11:47

It seems to me that building an Activity unit test with Robolectric\'s lifecycle utilities (starting with Robolectric.buildActivity()) and spying on the same Ac

相关标签:
2条回答
  • 2020-12-20 12:14

    At least for the case where the activity is not the object under test, but only a dummy activity which hosts a fragment under test, it is possible to inject a mock into the test activity which can verify interactions with the activity via the communication interface between fragment and activity (following http://developer.android.com/training/basics/fragments/communicating.html).

    0 讨论(0)
  • 2020-12-20 12:33

    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.

    0 讨论(0)
提交回复
热议问题