Jan 13

I was trying out mock objects today at work. I didn’t really know which implementation to choose. Both JMock and EasyMock seemed pretty good. But I eliminated EasyMock first because I’m just not a big fan of the whole record-replay thing. Then I spent about an hour trying to make JMock work. It sort of did. But I didn’t really like its expectation mechanism. Take an example from their own tutorial. To expect one invocation of add() method on a calculator object, I need to write something like this:

one (calculator).add(2, 2); will(returnValue(5));

That is just too redundant to me. It’s also hard to return value from the method under test so that the workflow can continue. Overall, it just didn’t feel right.

Just when I was about to give up and go back to use my own stub class, I came across a link on JUnit’s site that points me to SevenMock. I spent five minutes setting it up and another five minutes to write the first test using it. And I really liked it. It doesn’t use any fancy expectation syntax and doesn’t have the record-replay feature. The expectation is defined in the form of anonymous inner class. You can put whatever you’d like to assert right in the inner class. So the above example will look like this:

mockControl.expect(new Calculator() {
  int add(int a, int b) {
    assertEquals(2, a);
    assertEquals(2, b);
    return a + b;
  }
});

Notice the return line. You can have the right logic there so that the workflow can continue. Or you can have something that doesn’t make sense at all to test the sad case.

One thing though. SevenMock can only directly mock classes. So you’ll have to create an adaptor for interface or abstract class. But I don’t think that’s a big deal. My next post will explain another reason that made me choose SevenMock: the assertion of the parameters.

Leave a Reply

preload preload preload