Mockito an alternative to JMock
I’ve used JMock for quite some time and I’ve found it to be a great and very useful mocking framework for unit testing. I was never quite happy with the syntax though; especially the part where you specify expectations. Here’s a JMock snippet illustrating an expectation and a return value from a mocked object
context.checking(new Expectations() {{
oneOf (department).employees(); will(returnIterator(employees));
}});
In Mockito the equivalent code would look like this
when(department.employees()).thenReturn(employees);
I find the Mockito syntax to be easier to write and understand. I’ve seen fellow developers implement JMock expectations in a way where they actually didn’t perform a useful test, and I think the sometimes confusing syntax of JMock was the reason. I’m not dismissing JMock as an inferior mocking framework, but I do think that the learning curve is a bit steeper. If you haven’t used Mockito yet I encourage you to take a look at it.
Comments
2 Comments
how easy is it to migrate to mockito from Jmock if you have loads of JMock tests ?
I think it’s fairly easy to migrate tests from JMock to Mockito. Where I work we allow both of these frameworks and programmers are free to pick whichever they want within the same project. For us that prefer Mockito we typically leave the JMock tests in place unless there’s a reason to rewrite them. However if I have to add new tests I typically use Mockito over JMock .
Leave a Comment