Sunday, February 22, 2009

Servlet unit testing using Mockrunner

Servlet unit testing using Mockrunner (container free)

I had to write a servlet earlier this month and was looking for a way to do unit test for it. I was hoping that there is a way to do unit test for servlet. Right away, I knew it would not be straight forward as unit testing a regular simple java class. If you are familiar with servlet, of course you know that it depends on some other classes, such as HttpServletRequest, HttpServletResponse, etc.

So, one way of testing it, we need mock object. There is an excellent information about what mock object is all about by Martin Fowler, in this link.
While there are many other framework for JEE unit testing, I chose Mockrunner as the framework for my unit testing.

Download Mockrunner from the site, and include the library in your project. After that, create a test class which extends BasicServletTestCaseAdapter, so your test class would be something like the following:


public class MyServletTest extends BasicServletTestCaseAdapter {
// ...
}

then create an instance of the servlet you want to test, in this example would be MyServletTest:
protected void setUp() throws Exception
{
super.setUp();
createServlet(MyServletTest.class);
}



if your servlet requires parameter(s) then use addRequestParameter() method to set each one:
addRequestParameter("id", 1234);

The servlet that I created need to check the requested URL, so I had to find a way how to set it up. Fortunately, it is possible to do. Here's an example:
getWebMockObjectFactory().getMockRequest().setRequestURL("subscribe");

After all the setup done, it's time to test the servlet, by calling doPost() method, and check all actions that have been done.
I needed to check whether my servlet redirecting to the proper page afterwards. Here's how to do it:


MockHttpServletResponse response = getWebMockObjectFactory().getMockResponse();
assertEquals("redirect_location", response.getHeader("Location"));



I am glad I found this neat testing tool.

No comments:

Post a Comment