2017-10-15 86 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連接的片段。