Android: Writing test cases for Fragments

AnswerDroid picture AnswerDroid · Jun 18, 2015 · Viewed 24k times · Source

In my previous projects I've done most of the work through Activities and used ActivityInstrumentationTestCase2 as per the document:
http://developer.android.com/tools/testing/activity_testing.html
I have an idea how to work with Activity Test cases; but when it comes to Fragment ,I don't have much idea nor found much documents related to that. So how to write test cases when I have several fragments with one or two actvities? Any example code or sample would be more helpful.

Answer

Nachi picture Nachi · Jun 22, 2015

Here's a rough guide using ActivityInstrumentationTestCase2:

Step 1. Create a blank Activity to hold your fragment(s)

  private static class FragmentUtilActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      LinearLayout view = new LinearLayout(this);
      view.setId(1);

      setContentView(view);
    }
  }

Step 2: Inside your test, instantiate your fragment and add it to the blank activity

public class MyFragmentTest extends ActivityInstrumentationTestCase2<FragmentUtilActivity> { 
    private MyFragment fragment;

    @Before
    public void setup() {
        fragment = new MyFragment();
        getActivity().getFragmentManager().beginTransaction().add(1, fragment, null).commit();
    }
}

Step 3 Test your instantiated fragment

@Test
public void aTest() {
    fragment.getView().findViewById(...);
}

If you're using robolectric, this is pretty straightforward using the FragmentUtilTest class:

@Test
public void aTest() {
    // instantiate your fragment
    MyFragment fragment = new MyFragment();

    // Add it to a blank activity
    FragmentTestUtil.startVisibleFragment(fragment);

    // ... call getView().findViewById() on your fragment
}