Skip to main content

jMock 2 and my Java Unit Testing Toolkit

Posted by tomwhite on April 11, 2007 at 6:16 AM PDT

The long-awaited final version of jMock 2 was released today. There are some big changes since version one. For example, you can now write

Cat cat = mock(Cat.class);

and then set expectations on the returned cat object itself:

checking(new Expectations() {{

(This means that the miaow method is expected to be called exactly once on the cat object.)

This change means that you can refactor your method names without breaking your tests, unlike jMock 1 where the method names were strings:

Mock mockCat = mock(Cat.class);

You may have noticed that the new syntax is a little weird (check out the double braces, and how e.g. will modifiers need new statements), and it may take a little getting used to, but I think it's worth it for the IDE completion and refactoring support. For example, in test driven mode I can write the name of the method that doesn't yet exist then get my IDE to create the method for me.

The other nice thing is the integration with Hamcrest (a library of matchers that I've written about before). My toolkit for writing new unit tests now includes:

  1. Hamcrest for making flexible assertions.
  2. jMock 2 for defining expected behaviour.
  3. Responsible Naming for understanding what the test does.
Related Topics >>