Thursday, June 28, 2007

Wow! JMock has completely changed its api, ... for the better

I have been a long time user of jmock 1.x and suddenly had the need of jmock in a new project. So, I went and took the latest and greatest release and started mocking.

But what the...? It did not work as I was used to.

So, I went to look at the documentation and found the apis completely rewritten.

Gone are constructs like this:
   mockSubscriber.expects(once()).method("receive").with( eq(message) );
Where the method mocked is inside a string literal.
Say hello to the new way:
   context.checking(new Expectations() {{
one (subscriber).receive(message);
}});
The method call one(subscriber) takes the subscriber mock (which is typed as the class being mocked), and returns an instance of that very same type (using generics).

Expressing the mock expectations by simply calling methods on an actual instance of the mocked class is nice, as it makes refactoring in IDEs easier. Actually, I think this is what easymock have been doing for quite some time now :-)

JMock uses something called hamcrest to match the expectations with what is actually executed when the test is running. It is also nice to see, that jmock has kept its fluent interface style of writing tests. I like that.

Actually, come to think of it, I think one of my good and really clever colleagues told me this in a tech-session he hosted at work. Hmm, I have been slow in the uptake of this one :-)

No comments: