This post suggests both- that there is a difference (see comment by user SnoopyMe) and that the two can be used interchangeably. The EasyMock documentation makes no mention of any difference.
Is there any difference, either practically or semantically? If so, when is it more appropriate to use one over the other?
EDIT:
The following test suggests that there is a difference, at least when used with a strict mock:
@Test
public void testTestMe() {
Bar bar = createStrictMock(Bar.class);
expect(bar.doBar()).andReturn(1).anyTimes();
expect(bar.doOtherBar()).andReturn(2).once();
replay(bar);
Foo foo = new Foo(bar);
foo.testMe();
verify(bar);
}
@Test
public void testTestMeAgain() {
Bar bar = createStrictMock(Bar.class);
expect(bar.doBar()).andStubReturn(1);
expect(bar.doOtherBar()).andReturn(2).once();
replay(bar);
Foo foo = new Foo(bar);
foo.testMe();
verify(bar);
}
public class Foo {
private final Bar _bar;
public Foo(Bar bar) {
_bar = bar;
}
public void testMe() {
_bar.doBar();
_bar.doOtherBar();
_bar.doBar();
}
}
andReturn(...).anyTimes() still verifies order, which is enforced by the strict mock on verification. andStubReturn(...), however, does not.
However, it's still not clear to me if this is the only difference, or what the semantic difference is. For example, is anyTimes() the same as stubReturn() for a regular (not strict) mock?
The difference is tiny in terms of results. For a normal mock, it is the same. However, for a strict mock, the stub can be called at any time without any respect for the ordering. anyTimes
can be called any times but only in the recorded order.
This difference is caused by the semantic difference. A stub is something that can be called at any moment during the test and you don't really care when and how many times. In fact, most mocked methods are stubs in general.
Then anyTimes
means that you do care. But in fact, I never use it. When I do a test, I know what is gonna happen. My methods are always stubbed or expected to be called an exact amount of time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With