Question

I ran across some EasyMock 1 legacy code that looks like this:

service.convertValue("value");
control.setDefaultReturnValue(new Integer(1));
//Run code that calls that method

When upgrading to EasyMock 2, I converted it to the following (noting from this answer that setDefaultReturnValue() is equivalent to andReturn().anyTimes()):

expect(service.convertValue("value").andReturn(new Integer(1)).anyTimes());
//Run code that calls that method

But now I'm getting the error Unexpected method call convertValue("123")

It's obvious that in the original code, "value" was supposed to just be a placeholder. But aside from that, why did this work in EasyMock 1 but not EasyMock 2?

Was it helpful?

Solution

Buried in the EasyMock 1.2 documentation is a single setence that explains this issue:

The following code configures the MockObject to answer 42 to voteForRemoval("Document") once and -1 for subsequent calls as well as all other arguments to voteForRemoval():

mock.voteForRemoval("Document");
control.setReturnValue(42);
control.setDefaultReturnValue(-1);

(Empahsis mine)

In other words, setDefaultReturnValue() not only returns -1 for voteForRemoval("Document") after the first time, but also returns -1 if any other parameter is passed in. It looks like the person who wrote the test you're looking at knew this and just figured he'd throw in a placeholder, not caring about the actual parameter.

The EasyMock 2/3 equivalent of your code would be:

expect(service.convertValue(isA(String.class))).andReturn(new Integer(1)).anyTimes();

EasyMock 2 cleaned up a lot of ambiguities like this and forced developers to explicitly define what they were looking for. It's probably for the best, given the unintended side effects that can occur with the old style.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top