Monthly Archives: November 2015

TDD in Android using Robolectric

So I long time ago I started this project called MLBB – My Little Black Book. Sadly I had little time to actually work on it so it kind of died from natural causes… But that short experience and left me a bit confused. As much as I liked TDD applying these methodologies to the UI was a problem. Then I came across Robolectric and thought I found the silver bullet that I was looking for. Well, after trying it our a bit I noticed a few issues with it:

Slowness

Running the unit tests was slow. Even though that they should be “just” JUnit tests, running the actual tests was slow. It kind of defies the purpose of the whole thing I guess. Though this is not the only reason to use Robolectric, I found it to be the biggest issue, because the rest of the advantages of this framework (running in a CI server for example) were irrelevant for my simple app as a single developer.

Implicit Bad Design

What do I mean by that? if you unit test your Fragments and Activities, you can end up putting logic in them because it is easy to unit test that, so why not? Doing so leaves you with huge Activities and Fragments without separation of concerns between UI and logic. I design pattern like MVVM in this case will be very beneficial.

Testing on Actual Devices it What I Really Wanted

The Android ecosystem is very fragmented, that it a known issue that every Android developer faces. Many things that work on one device might not work on another, even though that on paper they have the same OS version. Each vendor creates his own flavour of the Android OS and all kind of bugs are introduced (for example – multidex support in Galaxy S5 and S6 devices with a specific build). There is no real substitution for testing on actual device and those are tests that you can automate with the Instrumentation tests. Combining these tests with MVVM while covering the ViewModel with JUnit tests basically give you a similar cover that Robolectric does, but with a good separation of concerns and actual devices tests.

Though still in Beta, Android Data Bindings is in Beta now, but soon to be released and that will allow developers to use MVVM easily. My new approach that I am going to take with the MLBB project is as follows:

  1. Define the interface of the ViewModel.
  2. Implement the UI on a Stub ViewModel.
  3. Use TDD to implement the ViewModel with simple JUnit tests.

Using TDD for UI is a bit of an over kill in this case and doesn’t really give you much. You can still use TDD for the UI logic and application logic and just leave the actual rendering to the Fragments/Activities. These can be tested using Instrumentation tests to be run on the emulator or actual devices.

Advertisements