Ersen Osman Ersen Osman - 2 years ago 153
Android Question

Android Espresso: How do I test a specific Fragment when following one activity to several fragment architecture

My app consists of one

Activity
for many
Fragments
.

I wish to use Espresso to test the UI of the
Fragments
. However I ran into a problem.

How can I test a
Fragment
which is not added to an
Activity
in
onCreate
. All examples I have seen with
Fragments
involve the
Fragment
being added in
onCreate
.
So how can I tell Espresso to go to a specific
Fragment
and start from there?

Thanks

Answer Source

Espresso can test Fragments only if they are displayed. And that requires them to be displayed by an Activity.

With your current setup you'll have to use Espresso to click() your way (like a user would) to the Fragment you actually want to test.

In one of my projects I have a ViewPager that displays Fragments. For those Fragments I use a custom FragmentTestRule to test them in isolation. I can start each Fragment directly and use Espresso to test it. See this answer.

You could also:

  • Do not use Fragments. Activities are easier to test. You can test each Activity on its own. In most cases Fragments offer no advantage over Activities. Fragments just make the implementation and testing more difficult.
  • Enable your FragmentActivity to directly show a certain Fragment when it is created. E.g. by supplying a special intent extra to your FragmentActivity. But this would add testing code to your app, which is generally not a good solution.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download