How do I get a reference to a fragment from within a unit/robotium test?


How do I get a reference to a fragment within Robotium unit test. In my case the fragement houses a WebView. I want to use solo to get reference to the fragment? How can this be done? btw, I have asked three robotium/android questions before without a vote up and without a response! Lets not neglect testing. At least value the question please.

  • You must to post comments

I have been away from robotium (and SO) for a little while but you used to be able to do the following because robotium has no inbuilt way to get the fragment.

The first step is you need the current activity which is easy enough:

Activity current = solo.getCurrentActivity();

If you look over the Android activity API you will notice it has the method getFragmentManager() and then if you follow that you will find methods named findFragmentByXXX();

so the code becomes:

Fragment fragment = solo.getCurrentActivity().getFragmentManager().findFragmentByID(xxx);

you will then have your fragment!

There is one issue with this potentially though, some activities do not have the getFramentManager() method they instead have the method getSupportFragmentManager() which works the same but gave fragment support to older devices, so you may need to use one or the other. If you need to support both you will have to do some reflection to determine which method to call unfortunately.

  • You must to post comments
Showing 1 result
Your Answer
Post as a guest by filling out the fields below or if you already have an account.