Mock No Longer Being Called When Converting from EasyMock 1 to EasyMock 2/3

旧时模样 提交于 2019-12-12 04:37:41

问题


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?


回答1:


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().



来源:https://stackoverflow.com/questions/21196140/mock-no-longer-being-called-when-converting-from-easymock-1-to-easymock-2-3

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!