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

My HSQLDB schema inspection story

This is a simple story of my need to inspect the schema of an HSQLDB database for a participar FOREIGN KEY, and the interesting things I had to do to actually inspect it. I am using an HSQLDB 1.8 database in one of my web applications. The application has been developed using the Play framework , which by default uses JPA and Hibernate . A few days back, I wanted to inspect the schema which Hibernate had created for one of my model objects. I started the HSQLDB database on my local machine, and then started the database manager with the following command java -cp ./hsqldb-1.8.0.7.jar org.hsqldb.util.DatabaseManagerSwing When I tried the view the schema of my table, it showed me the columns and column types on that table, but it did not show me columns were FOREIGN KEYs. Image 1: Table schema as shown by HSQLDB's database manager I decided to search on StackOverflow and find out how I could view the full schema of the table in question. I got a few hints, and they all pointed to

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

Fuctional Programming Principles in Scala - Getting Started

Sometime back I registered for the Functional Programming Principles in Scala , on Coursera. I have been meaning to learn Scala from a while, but have been putting it on the back burner because of other commitments. But  when I saw this course being offered by Martin Odersky, on Coursera , I just had to enroll in it. This course is a 7 week course. I will blog my learning experience and notes here for the next seven weeks (well actually six, since the course started on Sept 18th). The first step was to install the required tools: JDK - Since this is my work machine, I already have a couple of JDK's installed SBT - SBT is the Scala Build Tool. Even though I have not looked into it in detail, it seems like a replacement for Maven. I am sure we will use it for several things, however upto now I only know about two uses for it - to submit assignments (which must be a feature added by the course team), and to start the Scala console. Installed sbt from here , and added the path