Question

I have a test that includes the following EasyMock 1 code:

persistenceManager.getCount(linkCodeAttributeCriteria);
persistenceManagerControl.setDefaultReturnValue(0);
persistenceManagerControl.replay();
//Run a method
persistenceManagerControl.verify();

Now that my company is finally upgrading their EasyMock code, I have changed it to the following code:

expect(persistenceManager.getCount(linkCodeAttributeCriteria)).andReturn(0);
replay(persistenceManager);
//Run a method
verify(persistenceManager);

But suddenly the test fails saying that getCount was expected to be called one time, but was called 0 times. This is the only piece of code I have touched. Why is this test failing?

Was it helpful?

Solution

In EasyMock 1, there were two return methods for MockControl: setReturnValue() and setDefaultReturnValue(). Although similar, they have a subtle distinction: the first expects the method to be called one time, the second expects the method to be called zero or more times. The code in the question uses the latter.

To put it another way:

EasyMock 1                                  | EasyMock 2 and EasyMock 3
---------------------------------------------------------------------------------
setDefaultReturnValue(o)                    | andReturn(o).anyTimes()
setReturnValue(o, MockControl.ZERO_OR_MORE) | andReturn(o).anyTimes()
setReturnValue(o)                           | andReturn(o) or andReturn(o).once()
setReturnValue(o, 1)                        | andReturn(o) or andReturn(o).once()

In fact, you'll notice that in EasyMock 1, setDefaultReturnValue(o) is equivalent to .setReturnValue(o, MockControl.ZERO_OR_MORE). Substituting the equivalency into your old code will still make it run, but dropping the number of times argument or changing it to anything else will cause the test to fail because the method was not called enough times.

It seems that the developers of EasyMock decided to simplify things by only having one return call (probably a good move, given this confusion), andReturn(o), rather than two different ones, as well as making a "zero times or more" and explicit call via .anyTimes(). As with EasyMock 1 setReturnValue(), one time is still the default in EasyMock 2 and 3, which can either be called with an implied andReturn(o) or with an explicit andReturn(o).once().

If you need to keep the behavior in EasyMock 2/3 format, then replace setDefaultReturnValue(o) with andReturn(o).anyTimes().

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