Aug 04 2009

Mockito an alternative to JMock

Published by michael at 10:35 pm under Java, Testing

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.

Share and Enjoy:
  • Print
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • Blogplay
  • Technorati
  • Twitter

No related posts.

2 responses so far

2 Responses to “Mockito an alternative to JMock”

  1. Mikeon 09 Jun 2010 at 7:30 am

    how easy is it to migrate to mockito from Jmock if you have loads of JMock tests ?

  2. michaelon 16 Jul 2010 at 9:52 am

    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 .

Trackback URI | Comments RSS

Leave a Reply