Android Fragment Test with Espresso + Mockk + Kotlin

Brian Wang
3 min readJul 7, 2020

--

Testing Android fragment in isolation can be sometimes challenging due to the fact that fragments serve as reusable containers within your app and they can be used anywhere throughout the app. This makes it even more important to make sure that they function consistently and provide a resource-efficient experience. This is where FragmentScenario comes into play, a library introduced by AndroidX.

In this post, I’m going to demonstrate how to test a fragment in isolation which follows MVVM architecture with mock Repository for its ViewModel and interaction with UI objects using Espresso:

Add dependencies to build.gradle file

We need to define the fragment-testing artifact to use FragmentScenario:

Prepare mock data

To use a mock repository in our test, instead of using a dependency injection framework like Dagger or Koin, we can make a slight adjustment to the fragment to take in a repository in the constructor and pass it along to the ViewModelFactory:

Now our ViewModel is using a repository that we choose. Create a file to store and return some mock data. Mock the repository used in ViewModel with Mockk and initialize our fragment with the mock repository in our test:

Make ViewModel return our mock data

We can use every to return our mock data when certain functions are called. You can think of it as the when().thenReturn() in Mockito:

Launch fragment

We need to launch our fragment in a container in order to test its behaviors in isolation.

UI Tests

Now we can write some UI tests with Espresso:

You can learn more about Espresso in this wonderful medium article. You will use it a lot as it provides very powerful APIs to interact with UI objects on the view. And we can write custom matchers to match complicated UI objects which I will talk more about in another post.

Conclusion

If you follow along you will end up with a test similar to this:

I hope you get a general idea now about FragmentScenario, Espresso, and Mockk and how to bootstrap them together to create an isolated UI test for your fragment. If you have enjoyed this article please give it a clap, I will see you in future posts.

If you want to learn about E2E automation test: Android E2E Automaton Test with UI Automator

--

--

Brian Wang
Brian Wang

Written by Brian Wang

Self Developer | Tech Junkie | Professional Nap Taker 🐨

Responses (1)