2017-10-15 43 views
0

我正在为我的应用程序编写测试用例,它对于活动很有效。但是当涉及到ViewPager中的碎片时,我的情况就会失败。Android Espresso如何为碎片及其孩子的Acitivty写案例?

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

公共类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)); 
} } 

因此,谁能告诉我怎么到这儿来这个问题? 谢谢, K.拉杰什

+0

可能因为您正在调用launchActivity(null);所以视图将为空/空。 –

+0

@ H.Brooks,launchActivity()具有Intent参数。如何发送片段? – itsrajesh4uguys

回答

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

不好。它给出了下面的例外** java.lang.NullPointerException:试图调用虚拟方法'android.support.v4.app.FragmentManager com.MyActivity.getSupportFragmentManager()'**上的空对象引用 – itsrajesh4uguys

0

使用我发现我的上述问题的解决方案。这是代码片段。

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

从这种方式,你可以访问所有与Viewpager连接的片段。