Skip to main content

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.

Comments

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

Popular posts from this blog

Commenting your code

Comments are an integral part of any program, even though they do not contribute to the logic. Appropriate comments add to the maintainability of a software. I have heard developers complain about not remembering the logic of some code they wrote a few months back. Can you imagine how difficult it can be to understand programs written by others, when we sometimes find it hard to understand our own code. It is a nightmare to maintain programs that are not appropriately commented. Java classes should contain comments at various levels. There are two types of comments; implementation comments and documentation comments. Implementation comments usually explain design desicisions, or a particularly intricate peice of code. If you find the need to make a lot of implementation comments, then it may signal overly complex code. Documentation comments usually describe the API of a program, they are meant for developers who are going to use your classes. All classes, methods and variables ...

Inheritance vs. composition depending on how much is same and how much differs

I am reading the excellent Django book right now. In the 4th chapter on Django templates , there is an example of includes and inheritance in Django templates. Without going into details about Django templates, the include is very similar to composition where we can include the text of another template for evaluation. Inheritance in Django templates works in a way similar to object inheritance. Django templates can specify certain blocks which can be redefined in subtemplates. The subtemplates use the rest of the parent template as is. Now we have all learned that inheritance is used when we have a is-a relationship between classes, and composition is used when we have a contains-a relationship. This is absolutely right, but while reading about Django templates, I just realized another pattern in these relationships. This is really simple and perhaps many of you may have already have had this insight... We use inheritance when we want to allow reuse of the bulk of one object in other ...

Planning a User Guide - Part 3/5 - Co-ordinate the Team

Photo by  Helloquence  on  Unsplash This is the third post in a series of five posts on how to plan a user guide. In the first post , I wrote about how to conduct an audience analysis and the second post discussed how to define the overall scope of the manual. Once the overall scope of the user guide is defined, the next step is to coordinate the team that will work on creating the manual. A typical team will consist of the following roles. Many of these roles will be fulfilled by freelancers since they are one-off or intermittent work engagements. At the end of the article, I have provided a list of websites where you can find good freelancers. Creative Artist You'll need to work with a creative artist to design the cover page and any other images for the user guide. Most small to mid-sized companies don't have a dedicated creative artist on their rolls. But that's not a problem. There are several freelancing websites where you can work with great creative ...