安卓浓缩咖啡如何为片段及其子级从活动编写案例?



我正在为我的应用程序编写测试用例,它适用于活动。但是当涉及到ViewPager中的片段时,我的案例失败了。

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

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

如何克服此问题?

我已经

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

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

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

对于 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()));
    ....
    ...

最新更新