Mock objects on Android with Borachio: Part 2

In part 1 of this series, I showed how to mock an interface that we created ourselves under Android. That’s useful, but mocking really pays dividends when mocking OS services—doing so allows us to test our code in isolation, verify that it interacts with the OS correctly and that it handles errors properly.

But there’s a wrinkle. Android is the most test-hostile environment I’ve ever had the misfortune to find myself working in. I wonder sometimes if its designers deliberately designed it to make testing as difficult as they possibly could. It can be done, and I’ll show how in part 3, but if you’ll forgive me a digression, in this article I’m going to try the simple, “obvious” solution and demonstrate why it doesn’t work.

I’m going to try to write a simple test of an application that uses Android’s PowerManager service. PowerManager allows us to control when the device switches on or off. If we’re about to start some critical operation that must complete without the device switching off, we can obtain a WakeLock, which is what this sample app does.

Failure in testAttempt1:
junit.framework.AssertionFailedError
at android.test.ActivityUnitTestCase.startActivity(ActivityUnitTestCase.java:148)

Hmm—apparently this isn’t going to be as easy as we hoped.

The problem is that startActivity calls our MockContext. Specifically it calls getSystemService("layout_inflater") which fails because MockContext‘s methods are non-functional and throw UnsupportedOperationException.

It turns out that what Android means by “mock” isn’t what the rest of the world means. As Martin Fowler says in Mocks Aren’t Stubs, mocks are:

objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

Never mind—there is another way. Android’s ContextWrapper allows us to wrap an existing context, only changing those bits of functionality we’re interested in for the purposes of our test:

Error in testAttempt3:
java.lang.IllegalArgumentException: android.os.PowerManager is not an interface

Borachio, in common with most other mocking frameworks, can only mock interfaces, and PowerManager is a class, not an interface. There are mocking frameworks that can mock classes, for example PowerMock, but they rely on code generation, which Android’s Dalvik VM doesn’t (yet) support. So that’s not going to be any help :-(

There’s one final thing we can try. As well as mocking interfaces, Borachio can also mock functions. So we can derive from PowerManager and just mock the single method we’re interested in like this: