EasyMock experience

1 minute read

For the last two weeks I’ve worked with EasyMock and coming from a JMock background it’s easy to make a comparison between the two libraries.

I have to say that I’m less than impressed by EasyMock: the whole concept of the two different states (recording and active) for the mock library looks unreasonable.

Let’s look on how we can create a mock with EasyMock:

MyInterface mock =EasyMock.mock(MyInterface.class); //expectation mock.myMethod(); //activation step mock.replay(); //actual call to the mock mock.myMethod(); //verification that the method has been called mock.verify();

There’s also a more DSLish style of defining expectations, that I personally prefer (it differentiates clearly the definition of the expectation from the actual method call).

EasyMock.expects(mock.myMethod());

This style is the only one available when the expectation is more complex:

EasyMock.expects(mock.myMethod()).andReturn(true);

But what if I want to define that a certain method will be called on the stub, no matter how many times ?

I can either use a different way of creating the mock: EasyMock.createNiceMock(MyInterface.class);

or using the DSL way:

EasyMock.expects(mock.myMethod()).anyTimes()

I think that having two ways of defining the same expectation is pretty confusing, specially when you’re using the API for the first time. What I’m looking for in a mock library is the capability of defining the expectations in a coincise but expressive way and then inject the dependency in the object I want to test.

JMock2 is pretty close, but I have to admit the the inner class notation with all those curly brackets around is not helping.

A fellow ThoughtWorker have just released Mockito: it looks like it’s taking the best from EasyMock and JMock and put in a single library. Might be worth a try.

Updated: