I know there is a Robolectric.shadowOf(Fragment) method and a ShadowFragment class, thought they aren’t listed on the docs, but I can’t make it work.
myFragment = new MyFragment();
myFragment.onCreateView(LayoutInflater.from(activity), (ViewGroup) activity.findViewById(R.id.container), null);
myFragment.onAttach(activity);
myFragment.onActivityCreated(null);
I’m working with API level 13 (Honeycomb).
Thanks.
Edit #4 & #5: In Robolectric 3.*, they split up the fragment starting functions.
For support fragments, you will need to add a dependency to your
build.gradle:Import:
org.robolectric.shadows.support.v4.SupportFragmentTestUtil.startFragment;For platform fragments, you don’t need this dependency. Import:
import static org.robolectric.util.FragmentTestUtil.startFragment;
They both use the same name of
startFragment().Edit #3: Robolectric 2.4 has an API for support and regular fragments. You can either use the
newInstance()pattern or use the constructor when constructing yourFragment‘s.Edit #2: There’s a new helper if you’re using support fragments (one that supports regular activities/fragments should be in the next release):
Edit: If you upgraded to Robolectric 2.0:
Original answer
As the other commenter suggested, you do need to use the fragment manager (instead of calling the lifecycle methods you listed above).
I create a test runner and have a function that starts up a fragment for me so I can use it everywhere.