Mock objects on Android with Borachio: Part 1

May 5, 2011

In the next few “Technical Wizardry” articles, we’re going to look at the approach we’ve developed to help with testing Android code (first published here).

One of my biggest frustrations with writing code for Android has been the fact that none of the current Java mocking frameworks work on Android’s Dalvik VM. I recently released Borachio a native Scala mocking framework which does work on Android.

Because Borachio is written in Scala, you’ll need to write your tests in Scala. But it can be used to test code written in Java.

This post demonstrates how to get basic mocking working. Things get more complicated when you try to mock bits of Android itself, but I’ll cover that in a subsequent article.

This is an Android version of the example in Martin Fowler’s article Mocks Aren’t Stubs. The code is checked into GitHub here. You’ll need to have the Android SDK and Scala 2.8 installed to run this code.

We’re going to build a (very) simple ordering system. Orders will succeed if there’s enough inventory in our warehouse and fail if not. Let’s start by creating a very simple little Android application for us to test:

  1. Create a new project with:
  2. The core abstraction is a warehouse, represented by a Warehouseinterface:
  3. And here’s a very simple concrete implementation of Warehouse:
  4. We remove things from the warehouse by placing an Order:
  5. We’ll need a UI to allow us to make orders, so modify main.xmlto look like this:
  6. And finally, here’s the implementation of WarehouseManager:

You should now have a little Android application that can be compiled and installed with ant install. Here’s what it looks like:


So, now that we’ve got something to test, let’s create a test project to test it:

  1. Create a test project with:

    Next, we’ll convert this to a Scala project, as described here.
  2. Add scala.dir and proguard.dir to Here’s what I added to mine (you’ll need to change the paths to match your local installation):
  3. Copy build-scala.xml into the root of the test project and add the following to build.xml:
  4. Delete the proguard.cfg file and copy the configs directory into the test project. Add the following to the bottom of both default-debug.cfg and default-release.cfg(to ensure that ProGuard doesn’t discard our test classes:
  5. Copy the Borachio JAR to the libs directory.
  6. Finally, we can write our tests, which create mock instances of the Warehouseinterface:
  7. Run the tests with:

In part 2, we’ll look at some of the challenges of mocking Android components.