I've been looking for a way to test the UI of my Fragments separately (ie, independently from other fragments and activities) but I can't find a way to do it.
In particular, let's say I have Fragment A, Fragment B and Fragment C. The only way (app-wise) to go to Fragment C is by passing through Fragment A and Fragment B first. I am looking for a way to test Fragment C directly (potentially by mocking its dependencies, if any exists), without having to pass through Fragment A and B.
Tools I investigated so far:
monkey: only used to generate pseudo-random events through command line. Not what I want.
monkeyrunner: it can run Python programs to send event streams to my Android app, but it cannot target a particular Fragment directly with those scripts.
Espresso: white-box testing tool. This comes close to what I want, but it still requires passing through Fragment A and B before reaching Fragment C (ie, you need to start your app and then the tests will run from there).
UI Automator: black-box testing tool. This also comes close, but again, it requires passing through the previous Fragments before testing the one I want (Fragment C).
Is there any way to test the UI of a Fragment directly?
You can use Robotium.This is for android UI testing.
I'm am using a custom
FragmentTestRule
and Espresso to test each of myFragments
in isolation.I have a dedicated
TestActivity
that shows the testedFragments
in my app. In my case theActivity
only exists in thedebug
variant because my instrumentation tests run againstdebug
.TL;DR Use the awesome FragmentTestRule library by @brais-gabin.
1. Create a
TestActivity
insrc/debug/java/your/package/TestActivity.java
with a content view where the testedFragment
will be added to:2. Create a AndroidManifest.xml for the
debug
variant and declare theTestActivity
. This is required to start theTestActivity
when testing. Add this Manifest to thedebug
variant insrc/debug/AndroidManifest.xml
:3. Create the
FragmentTestRule
in theandroidTest
variant atsrc/androidTest/java/your/test/package/FragmentTestRule.java
:4. Then you can test
Fragments
in isolation:I developed FragmentTestRule an Andorid library using the @thaussma's idea. It allows you to test your
Fragment
s in isolation.You just need to add this:
More information here.