Integration testing with Robolectric

Chuck Greb
Android Testing
Published in
2 min readJan 3, 2017

When I first started using Robolectric in late 2011 it was a literal godsend.

This amazing framework made it possible to unit test Android code in the local JVM using bytecode manipulation to replace Android classes with mock (shadow) classes.

At the time the only viable alternative was the original Android instrumentation testing framework based on JUnit 3 that has since been deprecated which required deploying your app (and an additional test app running in the same process) to an actual emulator or device.

DroidconUK: TDD Android with Robolectric by Joseph Moore (2011)

Early versions of Robolectric mocked (shadowed) all of the classes in the Android framework to work around the stub implementation of the SDK that your application was compiled against locally.

However over time Robolectric evolved to remove most of the shadows and use more of the real Android classes. While this change improved the realism of the testing environment it also came at a cost.

Robolectric tests are now slower to run and consume more memory. The framework is also more complex to accommodate things like multiple API levels and executing actual Activity and Fragment lifecycle events. All these things have started to make Robolectric feel less like a traditional unit testing framework.

Also now we have a mockable version of the Android JAR and real JVM unit testing integrated right into Android Studio.

So where does this leave Robolectric?

In my opinion Robolectric has now evolved to be more of an integration testing tool which is best suited for testing how your code interacts with the Android framework rather than in isolation. Integration tests are still a very important layer in the test pyramid but not the same as unit tests.

It should not be used for classes with little to no Android dependencies like models and presenters (which is where most of your logic should live anyway).

Robolectric can however be an effective way to test whatever logic inevitably needs to remain in your activities, fragments, and views without requiring UI tests on an emulator or device with a tool like Espresso.

The website includes a getting started guide and there also a number of sample projects.

Robolectric tests are also utilized for testing Android classes in my clean architecture example project.

--

--

Chuck Greb
Android Testing

Mission-driven engineering leader. Community organizer. Digital minimalist.