Android Espresso如何从Activity编写片段及其子元素的大小写?

问题描述 投票:0回答:2

我正在为我的应用程序编写测试用例,它对于活动很有效。但是,当涉及到ViewPager中的Fragment时,我的案例就失败了。

下面的测试用例失败,因为如果直接运行该片段,该片段将显示一个空视图。

public class SentimentsFragmentEspressoTest {

    @Rule
    public FragmentTestRule<SentimentsFragment> mFragmentTestRule = new FragmentTestRule<>(SentimentsFragment.class);

    @Test
    public void fragment_can_be_instantiated() {

        // Launch the activity to make the fragment visible
        mFragmentTestRule.launchActivity(null);

        // Then use Espresso to test the Fragment

        onView(withId(R.id.listSentiments))
                .perform(RecyclerViewActions.scrollToPosition(4));
    }
}

我该如何克服这个问题?

android android-fragments android-espresso
2个回答
0
投票

对于ViewPager中的片段,请尝试在您的测试中使用

@Rule
public ActivityTestRule<YourActivity> mActivityRule = new ActivityTestRule<>(YourActivity.class);

@Before
public void setUp() throws Exception {

    //get fragment
    mActivityRule.getActivity()
            .getSupportFragmentManager().beginTransaction();


}

@Test
public void testRecyclerView() {

    //click on item recyclerview
    onView(withId(R.id.listSentiments)).perform(RecyclerViewActions.actionOnItemAtPosition(0, click()));
    ....
    ...

0
投票

我已经找到了上述问题的解决方案。这是代码片段。

 ViewInteraction recyclerView = onView(
                       allOf(withId(R.id.listSentiments),
                               withParent(withId(R.id.viewpager)),
                               isDisplayed()));
               recyclerView.perform(actionOnItemAtPosition(3, click()));

通过这种方式,您可以访问与Viewpager连接的所有片段。

© www.soinside.com 2019 - 2024. All rights reserved.