When it comes to the automated testing of our android applications we may be using espresso to satisfy this requirement. If so, chances are that you’ve used espresso to test an activity in your application — this may have involved things such launching an activity, providing extras for the activity intent and checking some UI component state. Whilst this has always been well and good when it comes to activities, how have you handled the testing of fragments in your application? Chances are it’s been something along the lines of:

Launching the activity of your application which houses the fragment that you want to test

Creating a custom test rule that allows you to launch the fragment that you want to test in isolation

Whilst these two ways work, they both have their flaws. To begin with, launching the activity housing the fragment means that you are not testing that fragment in isolation — your test should only care about that fragment itself and not the parent containers of it. For example, if you’re using a bottom navigation view inside of an activity that also manages some behind-the-scenes state (such as an authenticated user for example) then this data is going to need to be handled within the test for your fragment — you may then run into having to mock many different requests for some things that the fragment doesn’t even care for. And then what if this housing activity then changes, are our fragment tests going to break as well as the activity tests? Whilst these are only simple points I hope it displays that like our application code, our tests should focus on their responsibility and remain lightweight. This will help to ensure that our tests remain maintainable, readable and also less likely to break as we move forward.

Moving onto the second point — this one is definitely a large improvement on the first. This allows us to launch our fragment in isolation and focus on what we are testing. This will either require using an external dependency (such as https://github.com/novoda/espresso-support) or writing your own implementation. However, these require either adding a dependency to your application or adding a small bit of boilerplate to your projects every time that you want to setup isolated testing. Not a huge deal, but it’s worth bearing these things in mind.