Sunday, April 19, 2009

Create mock objects with metaprogramming

We usually create mock objects in our test suites for those classes which communicate with some external entity that we cannot (or do not care to) setup in our test cases. However, mocking is possible only when we have used dependency injection properly. If we have classes that instantiate their own dependencies then we cannot mock the dependencies. Sometimes our mock solutions may also be time intensive at runtime. I will explain this later in the post.

One solution (the correct one) is to refactor the code and use proper dependency injection to allow classes be be mocked. However, when we have a huge code base of non DI code, which cannot all be changed at a time, then we just have to make so with fewer unit tests. But all is not lost. If we use a dynamic language like Groovy to write the test cases then we can use metaprogramming to change a classes methods at runtime instead of creating mock classes.

I am building a command line Twitter client in Groovy. I have a class called FriendsTimelinePlugin.groovy which periodically fetches content from the friends timeline service in Twitter. There is a class called Net which encapsulates code to make GET and POST reqests. The FriendsTimelimePlugin.groovy class uses Net.GET(url) to invoke Twitter's API to get the XML feed. I obviously did not want to connect to Twitter for the unit test.

I had two options. The first one was to start an instance of Jetty in the in memory mode and get FriendsTimelinePlugin to use a local URL which would talk to my local instance of Jetty instead of Twitter. I could then create handlers in Jetty to mock the reply. This is a good solution, but it would involve additional classes to create the mock handlers for Jetty and it is also time expensive to setup Jetty at runtime. If we have several such unit tests, then it would take enormous time to start and stop Jetty for each unit test.

Below I show an example of how I mocked Net.groovy and FriendsTimelinePlugin.groovy using metaprogramming while creating unit tests.



public void setUp() {
//mock Net.GET(...)
Net.metaClass.static.GET = { url ->
def xml
if(url.contains('since')) {
xml = """<statuses>
<status>
//not showing the entire string containing status code
</status>
</statuses>"""
return xml
}
else {
xml = """<statuses>
<status>
//not showing the entire status string
</status>
</statuses>"""
return xml
}
}

//change the output PrintWriter in FriendsTimelinePlugin
def mockedOut = new PrintWriter(new StringBufferWriter(_buff))
FriendsTimelinePlugin.metaClass._out = mockedOut
FriendsTimelinePlugin.metaClass.filter = ['user_one', 'user_two']
FriendsTimelinePlugin.metaClass.interval = 500
}



In Groovy we can change the implementation of a method using the class' ExpandoMetaClass. This is done by associating a closure with the method to change. In my code, FriendsTimelinePlugin.groovy invokes the Net.GET(url) method to make a GET request to Twitter. I redefined the GET method at runtime so that it does not do any network communication. Instead it will simply return an xml which otherwise would have been returned after fetching it from Twitter. If you look at the code above you will see a line similar to this



Net.metaClass.static.GET = { url ->
//mock implementation
//directly return XML
}



This code replaces the actual implementation of the GET method in Net.groovy with the implementation provided in the closure. The metaClass' static property is used because Get is a static method. As you can see the mock implementation returns an XML string directly instead of fetching it from Twitter.

If you look towards the end of the setup method I am also changing _out in FriendsTimelimePlugin. This is the output stream to which it prints the latest twits. In my test case I have redirected it from System.out to an output stream which writes to a StringBuffer whose contents can be verified in the test case.

I realize that if this mechanism of using metaprogramming instead of creating mock objects is used injudiciously then it could lead to really bad code. Especially dangerous is mocking select methods of a class without understanding how and where it is used in the entire codebase. This can lead to undesired side effects and a totally unmanageable test suite. However, if used carefully this mechanism can not only make it possible to write test cases for classes, which were earlier not possible, it can also reduce the time for running a test suite because we will not have to incur the cost of starting/stopping test servers.

1 comment:

Gerardo said...

Unfortunately, Groovy does not support mocking of static methods with its MockFor implementation. For those needing to test static methods with Groovy Mocks, I provide my own implementation of StaticMockFor here:

http://europatech.blogspot.com/2009/09/def-original-clazz_25.html