Unit testing

Mockery is a new JMock class. It allows you to create mock implementations of your interfaces in your unit tests.

In the days before Mockery, you could still use JMock’s Mock class and then use human-readable style of configuring the expectations. For example, to mock the Sender interface and its send(String s) method, you’d write

Mock sender = new Mock(Sender.class);
PostOffice postOffice = new PostOffice();
postOffice.setSender((Sender)sender.proxy());

sender.expects(once()).method(”send”).with(eq(”Hello”)).isVoid();
postOffice.post(”Hello”);

Now, assuming the PostOffice.post(String s) uses the Sender implementation to ultimately send the message, this test would work. However, if you refactored the Sender.send(String s) method, your IDE would not be able to refactor the JMock expectation.

Enter Mockery

The same code using JMock’s new Mockery class would look like this:

Mockery context = new Mockery();
final PostOffice postOffice = new PostOffice();
final Sender sender = context.mock(Sender.class);
postOffice.setSender(sender);

final String message = “Hello”;
context.checking(new Expectations() { {
    one(sender).send(message);
} });

postOffice.post(message);

Here you can see that the test still reads very well, but most IDEs will automatically refactor the unit test expectations whenever you refactor the Sender interface. Also notice that you do not need to explicitly state with(eq(”Hello”)) or with(eq(message)). Instead, you “call” the mocked method directly, passing it the values to be checked.

There is a lot more to Mockery, we recommend that you give it a fair try in your unit tests.

Leave a Reply