I want to unit test an Android Fragment class.
Can I set up a test using AndroidTestCase or do I need to use ApplicationTestCase?
Are there any useful exampl
Suppose you have a FragmentActivity class called 'MyFragmentActivity' in which a public Fragment class called 'MyFragment' is added using FragmentTransaction. Just create a 'JUnit Test Case' class that extends ActivityInstrumentationTestCase2 in your test project. Then simply call getActivity() and access MyFragment object and its public members for writing test cases.
Refer the code snippet below:
// TARGET CLASS
public class MyFragmentActivity extends FragmentActivity {
public MyFragment myFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
myFragment = new MyFragment();
fragmentTransaction.add(R.id.mainFragmentContainer, myFragment);
fragmentTransaction.commit();
}
}
// TEST CLASS
public class MyFragmentActivityTest extends android.test.ActivityInstrumentationTestCase2 {
MyFragmentActivity myFragmentActivity;
MyFragment myFragment;
public MyFragmentActivityTest() {
super(MyFragmentActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
myFragmentActivity = (MyFragmentActivity) getActivity();
myFragment = myFragmentActivity.myFragment;
}
public void testPreConditions() {
assertNotNull(myFragmentActivity);
assertNotNull(myFragment);
}
public void testAnythingFromMyFragment() {
// access any public members of myFragment to test
}
}
I hope this helps. Accept my answer if you find this useful. Thanks.