Mock objects on Android with Borachio: Part 3

May 5, 2011

As we saw in part 2 of this series, mocking Android’s PowerManager service directly is impossible. But there is an alternative approach that gives us something close enough. This article describes that approach.

The code of the application described here is checked into GitHub.

Given that we can’t mock PowerManager directly, instead we’re going to create an interface that we can mock:

Together with an implementation which will be used in production code:

We won’t be able to test this implementation, but hopefully it’s so simple that (as Hoare puts it) it obviously contains no deficiencies (as opposed to contains no obvious deficiencies).

But we do now have something that we can mock, so we can test that the code that calls it does so correctly.

The first challenge we’re going to have to overcome is how to inject a PowerControl implementation (the real one or the mock) into the code under test. We could use a dependency injection framework like RoboGuice, but for the purposes of this article I’m going to keep things simple and use a custom Application class which implements a getPowerControl method:

Our activity calls this during onCreate:

We can now write a test to verify that startImportant calls disablePowerOff:

Our test first creates a mock PowerControl object:

And then creates an application object that returns this mock instead of a “real” PowerControl instance:

We tell Android’s test framework to use this application object by calling setApplication:

Finally, we set our expectation (that disablePowerOff is called once) and call startImportant: