开发者

Difference between EasyMock.expect(...).times(...) versus using EasyMock.expect(...) several times?

What is the difference between this:

ResultSet set = EasyMock.createNiceMock(ResultSet.class);
EasyMock.expect(set.getInt("col1")).andReturn(1);
EasyMock.expect(set.wasNull()).andReturn(false);
EasyMock.expect(set.getInt("col2")).andReturn(2);
EasyMock.expect(set.wasNull()).andReturn(false);
EasyMock.replay(set);

assertEquals(1, set.getInt("col1"));
assertEquals(false, set.wasNull());
assertEquals(2, set开发者_JS百科.getInt("col2"));
assertEquals(false, set.wasNull());

And this:

ResultSet set = EasyMock.createNiceMock(ResultSet.class);
EasyMock.expect(set.getInt("col1")).andReturn(1);
EasyMock.expect(set.getInt("col2")).andReturn(2);
EasyMock.expect(set.wasNull()).andReturn(false).times(2);
EasyMock.replay(set);

assertEquals(1, set.getInt("col1"));
assertEquals(false, set.wasNull());
assertEquals(2, set.getInt("col2"));
assertEquals(false, set.wasNull());

?

Note: both sets of code compile and run successfully as jUnit tests. Also, note that the use of a "nice" mock is on purpose here.


To answer the question in your title - there's no difference. Calling x.expect(y).times(3) is exactly the same as calling

x.expect(y);
x.expect(y);
x.expect(y);

(Note that as pointed out by Andy Thomas-Cramer, your specific examples aren't entirely equivalent because the order of calls differ.)

This might just seem like a convenience issue. However there's a distinct difference beyond this: in that the times() case you can pass in the expected number of calls as a variable. Consequently you can make this configurable by some external file, or even simply by a public constant int which you also use to fire off the test harness. It's a lot more flexible than having to explicitly compile the correct number of calls to expect() (and update your code if you now need to test with five workers instead of three).


The second is simpler to read and write. However, it would fail if the mock were changed to a strict mock, in which order of calls is validated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜