Now I Like jMock Even More

I really find jMock to be a useful testing tool. Sometimes I get stumped by jMock because I want to mock a concrete class that doesn’t have a noarg constructor.

Often the best solution is to create an interface and the problem goes away. I prefer to create role interfaces rather than header interfaces.

Sometimes an interface doesn’t seem to be warranted so I sigh and go ahead and create a noarg constructor and try to make it clear in the code that the noarg constructor has only been introduced for test code.

When I introduce a noarg constructor on a class with final fields I have two choices: drop the final modifier from the field or assign some sort of a (possibly bogus) value to the field in the noarg constructor. Both choices pain me because I like to declare a classes’ collaborators to be final and to initialize them to valid values in the constructor. But I make my unsavory choice because I feel the ability to create isolated unit tests trumps other considerations.

I recently noticed that jMock 2 has been released. As I was comparing each version’s documentation I came across a jMock 1 page that showed me that I didn’t need to create noarg constructors just for testing. Instead I can use this syntax to mock a concrete class:

Mock mockedClass = mock(SomeClass.class,"mockList",
                        new Class[]{String.class, int.class},
                        new Object[]{"Hello", new Integer(1)

Sure the syntax is kinda ugly but just hide it away in a creation method. So now I like jMock even more. By the way, jMock 2 looks interesting (although it does require a Java 1.5+ runtime).

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply