I have a Fragment that I want to test. I created a test Activity to which I add this Fragment and run some Espresso tests.
However, Espresso does not find any of the views inside the Fragment. It dumps the view hierarchy and it is all empty.
I do not want to embed the Fragment in a test Activity. I want to just test the Fragment in isolation. Has anyone done this? Is there a sample that has similar code?
@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;
}
}