Testing Jetpack Compose

So far in the declarative UI world, I’ve had one problem… testing. I don’t want to have to run UI tests (on device / emulator) for everything.

It’s now far too easy to do something like this:

So we can end up with untested logic inside our views.

I’ve seen this problem also in SwiftUI; But not my darling Flutter because Widget Testing ❤️ … well it turns out there is a way for Compose using Robolectric…

Lets start with dependencies (version at the time of writing are the latest)

Then we can move onto test setup, as this requires a bit of boiler plate I decided to write a base class …. I know, I know… Composition over inheritance 😱 ... I don’t care. So here’s the base compose test class

Above we’re telling the test to run with Robolectric, giving a test application to avoid using the real application. When I tried this I got errors relating to “androidx.loader.content” so someone on StackOverflow (of course) had this snippet available.

Then we create the compose test rule to use inside our tests.

Now on to a real test:

We’re now able to test that the correct text is displayed given a value.

The testing is somewhat limited. But we can test if something is displayed, exists, perform a click, etc. As far as I can tell there is no way to test what parameters were sent into something, like testing the correct url was passed into an AsyncImage for example.

Tests run very quickly (with a short lead in for the first Robolectric test maybe 10 seconds)

A list of matchers and assertions can be found here https://developer.android.com/jetpack/compose/testing-cheatsheet

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store