How can I test fragments with Robolectric?

后端 未结 7 1087
萌比男神i
萌比男神i 2020-12-02 10:16

I know there is a Robolectric.shadowOf(Fragment) method and a ShadowFragment class, thought they aren\'t listed on the docs, but I can\'t make it w

7条回答
  •  有刺的猬
    2020-12-02 11:06

    Support fragments have been moved to module:

    shadows-support-v4

    (as of July,2015, Robolectric v3.0)

    Add a gradle dependency to app/build.gradle:

    testCompile 'org.robolectric:shadows-support-v4:3.0'
    

    Then import to your Robolectric test java class:

    import org.robolectric.shadows.support.v4.SupportFragmentTestUtil;
    

    Then you can start & use a support-v4 fragment for testing:

    @Test
    public void minimalFragmentTest() throws Exception {
        MyFunFragment fragment = new MyFunFragment();
        SupportFragmentTestUtil.startVisibleFragment(fragment);
        assertThat(fragment.getView()).isNotNull();
    }
    

    References:

    • github changelog, moving support fragments to different module

提交回复
热议问题