Using Reflection To Create Mock Objects
Well-established tools like Mockito and EasyMock offer a powerful range of features for defining and interacting with mock objects. I use both heavily in my unit tests, and would recommend them to anyone looking for a mocking framework. Sometimes, however, a real (i.e. non-proxied) collaborator is called for, or adding third-party libraries may not be an option. In most cases, a suitable object could be instantiated by calling the constructor and setting it as a dependency to the object under test. Suppose though that we have the following ‘Footballer’ class, and we want to write a test for the ‘getAvgGoalsPerGame()’ method:
We know that unless both of the ‘gamesPlayed’ and ‘goalsScored’ are
NullPointerException will be thrown, so we might initially write the test as
This is all well and good, but when the number of fields that need to be set increases, the unit
tests quickly become littered with code required to set up the mocks. In this case, it makes sense
to perform the initialisation outside the test class. A generic
MockObjectPopulator is therefore
required, and an outline of what this might look like is given in the example below:
In the above implementation, a map is constructed to associate the field names with their values, and this is then applied to the object passed as a parameter. Where the desired value for a field is not explicitly given in the map, a value is retrieved from the ‘DefaultValues’ class based on the declared type. An implementation of the DefaultValues class is given below. Note that it can be loaded with values either explicitly or through dependency injection.
Returning to our Footballer example, we can now write the unit test as follows:
All of the code in this example is now on GitHub, so feel free to reuse anything that you have found useful.