Thursday, April 22, 2010

Mockito

I've done a lot of automated testing with JUnitand StrutsTestCase, but have wanted to explore other areas like mocking and continuous integration. So I decided to try out a Java mocking framework. I read a few blogs and decided to give Mockito a try. It's definitely an easy setup - just copy one jar file into your project (or add it to the build path in Eclipse). I then went through this tutorial to get a feel for it.

Never having done mocking before, it took me a little while to get use to the syntax and how it worked. I definitely need to spend more time with it on a real project to get the full feel of it. Having glanced at other mocking frameworks like EasyMock, it seems Mockito is a bit more streamlined and clean. For instance, there's no need to call replay to start the mock. But they look quite similar. Did I read Mockito came from EasyMock?

One of the challenges with mocking in an existing project is that the code must written in expectation of doing mocking. It's not simple to just slide in some tests. To do mocking, the code needs to use dependency injection (so the mocked objects can be injected) and use interfaces. One of the systems I'm working on right now is a Struts MVC application. It has nice layers with actions and DAOs, so it was straight-forward to use JUnit to test the DAOs and StrutsTest for the actions. But I'm trying to find a way to apply mocking to it and can't - data source objects are instantiated within the DAOs and are concrete classes. I may be able to refactor the code but that becomes a much larger effort. This is a good reason why you need to think about testing as you start developing an application.

No comments:

Post a Comment