Android Fragment Testing: FragmentScenario

Dan Nesfeder
2 min readJan 21, 2019

--

Back in November, Google held their Android Dev Summit in Mountain View. Although I did not attend, I tried to watch as many sessions as possible — they were all recorded and posted to this YouTube playlist.

One talk which really stood out to me was Ian Lake’s Single Activity: Why, When, and How. I highly encourage you to give it a watch. It focused mainly on the new Navigation Architecture Component announced at I/O.

In the talk, Ian touched on a lot of great features of the new component including a new way to test a givenFragmentFragmentScenario. The general gist being a FragmentScenario will launch a Fragment in an empty Activity, handling the boilerplate code that would be needed to do this with a library like espresso. This means we can write concise and isolated tests for ourFragments.

Adding the dependencies:

In your app build.gradle:

implementation 'androidx.fragment:fragment:1.1.0-alpha03'debugImplementation 'androidx.fragment:fragment-testing:1.1.0-alpha03'

Test view is displayed:

A simple example is checking a View is displayed on when the Fragment is launched. I created a SplashFragment that is shown while asking for permissions.

@Test
fun testSplashImageIsDisplayed() {
launchFragmentInContainer<SplashFragment>()

onView(withId(R.id.splashImageView)).check(matches(isDisplayed()))
}

launchFragmentInContainer is the main code to look at here. When you run the test on a device, you can see this takes care of creating the empty Activity and adding the SplashFragment.

Text arguments are displayed:

You are able to take the tests even further — like adding custom arguments and adjusting the state of the Fragment:

val displayText = "Hello world!"
val args = Bundle().apply {
putString(DISPLAY_TEXT, displayText)
}
val scenario = launchFragmentInContainer<DisplayTextFragment>(args)
scenario.moveToState(Lifecycle.State.RESUMED)
// TODO Verify text is displayed in correct view

As the navigation architecture component becomes more popular, I’m excited to see how Android UI testing will continue to evolve. Please reach out with questions or comments!

--

--