Thursday, June 18, 2009

Mock Objects

TDD and Mock Objects

Been playing with this for some time now. Test Driven Development requires a change in approach on designing and developing code. My natural instincts are to understand the requirement, design contracts (interfaces), implement and then unit test them. TDD disrupts the natural cadence and adapting to this approach requires some diligence and discipline.

I have not entirely discarded this approach but read an interesting interview by Donald Knuth - http://www.informit.com/articles/article.aspx?p=1193856

So coming back to Mock Objects - here are my 2 cents. I feel that it makes sense to Mock Objects at early stage of development during the time the code is getting baked in. Some of things become difficult when you play with Mocks. For e.g. a method that does some heavy business logic where multiple objects collaborate, you end up mocking a lot of those. The test becomes that much more complex and you end up writing more code. Then there are frameworks... I looked at jmock and EasyMock. I discarded jmock soon when I realized that I cannot mock a class without an interface. I dont want to write interface for every object that I want to use. EasyMock gives a good classextension which is handy to mock classes and specific methods. However, what I found out this also needs methods to get/set the objects to mock.

For e.g.

UserService{
authenticate(...){
UserDao ud = new UserDao(); // Cannot mock UserDao which is instantiated within the method
ud.fetch(...);

}
}

So I end up writing a getter / setter method and then mock it and set it to what I want UserDao to do.

I can easily write a unit test that actually works with a sample db and provides me data driven simulation of all the logic. Isnt that what I am actually looking for? Isnt simplicity the overall concern of any code that you write and do you want to disturb this cadence by overly complicating without gaining much...

0 comments:

Post a Comment