EasyMock andReturn() vs andStubReturn()

Unit TestingEasymock

Unit Testing Problem Overview


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?

Unit Testing Solutions


Solution 1 - Unit Testing

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.

Solution 2 - Unit Testing

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);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGlideView Question on Stackoverflow
Solution 1 - Unit TestingBarendView Answer on Stackoverflow
Solution 2 - Unit TestingBenView Answer on Stackoverflow