Jan 14
Continue from the last post. Remember the JMock example I used? It’s a simple add() operation:
one (calculator).add(2, 2); will(returnValue(5));
Now, what if, just for fun, I used my own class called MyInteger instead of primitive int as the parameter for add() method? The expectation will be written like this:
one (calculator).add(new MyInteger(2), new MyInteger(2)); will(returnValue(5));
So I expect one single call to add() method with two parameters of type MyInteger. This simple expectation will fail miserably with JMock because it compare the expected parameters with the actual parameters using the equals() method. The persistence layer I’m using, like a lot of other similar products, prevents me from overriding the equals() method. So JMock is actually comparing the reference. I won’t be surprised if there is a workaround for it. But since I had SevenMock set up and running in ten minutes, I won’t spend my effort looking for those workarounds.
Tagged with:
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.
Tagged with: