What is the difference between using andReturn(T value)
vs andStubReturn(T value)
for EasyMock?
In what situation would you use andStubReturn()
where andReturn()
can't achieve the same result?
EasyMock is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. EasyMock is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.
Once created, a mock is in “recording” mode, meaning that EasyMock will record any action the Mock Object takes, and replay them in the “replay” mode. expect(…): with this method, we can set expectations, including calls, results, and exceptions, for associated recording actions.
You use a stub return for a method call on the mock that you expect to happen but aren't otherwise interested in. You use a regular return for a "regular" method call.
Consider the following method:
public void someMethod(String arg) { if (logger.isDebugEnabled()) { logger.debug("Calling doSomething() on service " + service.getName().hashCode()); } service.postMessage("{" + arg + "}"); if (logger.isDebugEnabled()) { logger.info("Finished calling doSomething() on service " + service.getName().hashCode()); } }
...where service
is a mockable field. The hashCode()
thing in the log statements is contrived, but the point is that your mock needs to respond to any number of calls to getName()
to avoid an NPE, while you couldn't otherwise care less about it.
When writing an EasyMock based unit test for this method, you'd andStubReturn()
the call to getName()
and use a normal andReturn()
for the call to postMessage(String)
. When you verify the mock object, it'll only consider the latter and your the test doesn't break if you change the log4j config.
An additional note for clarity.
If you use .andStubReturn() (or if you use .andReturn(foo).anyTimes()), there will be no minimum expected call count. So if you set a mock expectation using either of these two, and the mocked method is NOT called, the .verify() call will not assert.
Example that will NOT assert when the mocked method isn't called;
FooClass myFooClass = EasyMock.createNiceMock(FooClass.class); EasyMock.expect(myFooClass.someMethod(EasyMock.anyInt()).andStubReturn(true); EasyMock.replay(myFooClass); EasyMock.verify(myFooClass);
Example that WILL assert when the mocked method isn't called;
FooClass myFooClass = EasyMock.createNiceMock(FooClass.class); EasyMock.expect(myFooClass.someMethod(EasyMock.anyInt()).andReturn(true).atLeastOnce(); EasyMock.replay(myFooClass); EasyMock.verify(myFooClass);
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