Recently, I have been working on my news reader app for Hacker News, Materialistic. As in any news reader apps, one of the most popular user feature request is ability to choose between light/dark theme for reading preference. Fortunately, supporting multiple themes in Android is quite easy and natural (given that you started properly). This blog explains the approach used by Materialistic to support multiple themes.
Robolectric is pretty much the de facto unit test framework for Android nowadays. It’s great, it’s fast (much faster than the out-of-the-box Android instrumentation test), and it gives you back joy of writing unit tests.
So you enjoy it so much that over the time you add more and more tests to your test suite that it no longer feels that fast anymore everytime you rerun it for verification? Well, it still needs to launch a VM to execute your tests after all. To improve this, you can make use of Robolectric’s Gradle plugin configuration to filter only tests that need to be rerun.
Gradle plugin for Android is the official build tool for Android, and is getting better everyday with new features allowing you to customize your build process more and more. One of its feature is allowing one to inject resources that can have different values per build type/product flavor. We can utilize it to separate analytics data for development and production.
If you are keen on doing TDD with Android, you may have stumbled upon the dreaded java.lang.RuntimeException: Stub! when you try to test drive your code with different contexts as input. For us, most of the time we use context is to get some resources out of it, either string, bool, raw, you name it. These resources may change execution behavior, and thus we are required to test with different resources to cover all cases.
Soon you learn that it is not straightforward to get the default Android’s Context out of the way, even with MockContext. That is one of the reasons why we see test frameworks such as Robolectric (or mock framework such as Mockito, PowerMock) getting popular. While it is convenient to let Robolectric build an activity for you and use it as the context, or mock up your own context using Mockito, there is a more structured way of making Context work for you in testing.
An example of how to configure Jacoco task in your build.gradle to generate coverage
report for a multi-project Gradle setup. The script will iterate through a set of
dependencies that is manually specified and merge all .class and source files into
final Jacoco report.