Thursday, December 24, 2009

Mocking Objects To Unit Test Android OS Applications

First Things First
Testing applications for Android OS can be done in two ways:
  • test on the Android platform using android.test and android.test.mock classes, or
  • testing on the development machine using the regular Java VM and standard Java unit testing and object mocking frameworks.
The good discussion as to pros and cons of each is presented in this article by a Google developer (although not an Android developer). The conclusion was to use the second option, due to valid limitations ofTo the first approach.

Mocking

What are mock objects? They are fake objects that can pretend to the callers to be an object they pretend to be, but are under full control of the test. Full control means two things here:
  • The test can monitor what methods of a mock object are called during the test and what parameters are provided, and
  • The test can dictate what results a mock class should return, without having to actually use, or even implement the class that is mocked.
Why mock objects? Without mocking objects, unit testing is limited to cases where the class under test doesn't use any other classes, or may be just some basic classes. The fuller answer is to why, can be given the following answers. To simplify explaining these answers, let's assume that we want to test class A which uses class B:
  • If some of the class A results depend on class B results. Without using mocking, the test would include the testing of class B. Often, we want to be able to write a test that tests just a single class. Smaller tests can be less brittle, that is they don't break as often with the changes done to the code after the test has been written.
  • If using class B in the test environment is not practical. For example, if the class B is a database, a web service or a GPS module, both of which are tightly coupled to the real world.
  • If we want to test class A before class B is implemented, so it doesn't exists, yet.
  • In general, mocking allows us to test not only an internal code of class A, but also if it uses class B correctly. So, it tests the class collaboration.
For more info on this topic see wikipedia article or this.

What Tools Are Available for Mocking?
The least of tools is quite long. In last couple years, I used probably the following ones:
  • JMock
  • Easy Mock
  • Mockito
  • PowerMock
The reasons I moved from one framework to another are new features (PowerMock can mock even static and final methods) and simpler syntax/tests (esp. Mockito). Also, PowerMock is in a way a conglomerate of Mockito and EasyMock. Although, that means that sometimes, when you use PowerMock you have to use the Mockito, and sometimes the EasyMock like API's. The good part is, that onces you know what mocking is about, using different API's is not that different.

No comments: