AnswerDroid AnswerDroid - 6 months ago 68
Android Question

Android: Writing test cases for Fragments

In my previous projects I've done most of the work through Activities and used ActivityInstrumentationTestCase2 as per the document:

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.


Here's a rough guide using ActivityInstrumentationTestCase2:

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

  private static class FragmentUtilActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
      LinearLayout view = new LinearLayout(this);


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

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

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

Step 3 Test your instantiated fragment

public void aTest() {

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

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

    // Add it to a blank activity

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