android 如何使用Espresso独立测试一个Fragment?

pu82cl6c  于 2023-04-04  发布在  Android
关注(0)|答案(5)|浏览(238)

我想测试一个Fragment。我创建了一个测试Activity,将此片段添加到其中并运行一些Espresso测试。
然而,Espresso在Fragment中找不到任何视图。它转储了视图层次结构,并且全部为空。
我不想将Fragment嵌入到测试Activity中。我只想单独测试Fragment。有人这样做过吗?有没有包含类似代码的示例?

@RunWith(AndroidJUnit4.class)
class MyFragmentTest {

    @Rule
    public ActivityTestRule activityRule = new ActivityTestRule<>(
        TestActivity.class
    );

    @Test
    public void testView() {
        MyFragment myFragment = startMyFragment();
        myFragment.onEvent(new MyEvent());
        // MyFragment has a RecyclerView
        // onEvent is an EventBus callback that contains no data in this test
        // I want the Fragment to display an empty list text and hide the RecyclerView

        onView(withId(R.id.my_empty_text)).check(matches(isDisplayed()));
        onView(withId(R.id.my_recycler)).check(doesNotExist()));
    }

    private MyFragment startMyFragment() {
        FragmentActivity activity = (FragmentActivity) activityRule.getActivity();
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        MyFragment myFragment = new MyFragment();
        transaction.add(myFragment, "myfrag");
        transaction.commit();
        return myFragment;
    }
}
ekqde3dh

ekqde3dh1#

我将以如下方式创建ViewAction:

public static ViewAction doTaskInUIThread(final Runnable r) {
    return new ViewAction() {
        @Override
        public Matcher<View> getConstraints() {
            return isRoot();
        }

        @Override
        public String getDescription() {
            return null;
        }

        @Override
        public void perform(UiController uiController, View view) {
            r.run();
        }
    };
}

然后使用下面的命令启动应该在UI线程中运行的代码

onView(isRoot()).perform(doTaskInUIThread(new Runnable() {
        @Override
        public void run() {
            //Code to add your fragment or anytask that you want to do from UI Thread
        }
    }));

以下是添加片段视图层次结构的测试用例示例

@Test
public void testSelectionOfTagsAndOpenOtherPage() throws Exception{

    Runnable r = new Runnable() {
        @Override
        public void run() {
            //Task that need to be done in UI Thread (below I am adding a fragment)

        }
    };
    onView(isRoot()).perform(doTaskInUIThread(r));

}
h4cxqtbf

h4cxqtbf2#

public class VoiceFullScreenTest {
    @Rule
    public ActivityTestRule activityRule = new ActivityTestRule<>(
            TestActivity.class);

    @Test
    public void fragment_can_be_instantiated() {
        activityRule.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                VoiceFragment voiceFragment = startVoiceFragment();
            }
        });
        // Then use Espresso to test the Fragment
        onView(withId(R.id.iv_record_image)).check(matches(isDisplayed()));
    }

    private VoiceFragment startVoiceFragment() {
        TestActivity activity = (TestActivity) activityRule.getActivity();
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        VoiceFragment voiceFragment = new VoiceFragment();
        transaction.add(voiceFragment, "voiceFragment");
        transaction.commit();
        return voiceFragment;
    }

}

您可以从UI线程启动您的片段,如上所述。

yquaqz18

yquaqz183#

您可以使用androidx.fragment:fragment-testing库。在测试方法中启动片段非常简单:

val fragmentArgs = Bundle()
androidx.fragment.app.testing.launchFragmentInContainer<MyFragment>(fragmentArgs)

您可以在Test your fragments Android开发者指南中找到有关此库的更多信息。

l3zydbqr

l3zydbqr4#

您可以使用FragmentTestRule
而不是常规的ActivityTestRule,你必须用途:

@Rule
public FragmentTestRule<?, FragmentWithoutActivityDependency> fragmentTestRule =
    FragmentTestRule.create(FragmentWithoutActivityDependency.class);

你可以找到more details in this blog post

iaqfqrcu

iaqfqrcu5#

你可能忘了在视图层次结构中注入片段。尝试在TestActivity布局中定义片段的保持器容器(比如id为fragment_containerFrameLayout),然后使用add(R.id.fragment_container, myFragment, "tag")this method)代替add(myFragment, "tag")。我猜你也可以使用具有相同签名的replace方法。

相关问题