views:

93

answers:

1

I'm still a rather new developer,so I might not have a grasp on all the concepts and terms which could be the reason why I don't understand this. But what exactly is the difference between using andReturn(T value) vs andStubReturn(T value) for EasyMock?

Both of their parameter types are the same. In what situation would it require you do use andStubReturn() where using andReturn() couldn't achieve the same result? Because all of the tests I have written so far have been written with andReturn(), and I haven't run into any problems yet.

Isn't a stub object just a class that has implementations to all the methods defined in the interface with the expected return values put inside the method? Why would you need to do andStubReturn()?

+4  A: 

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.

Barend
so let me see if I understand this correctly. Basically andStubReturn() is used for methods that we do not care about for our test for the mock objects , but we're required to mock the return otherwise, the code will not function. The andStubReturn() methods aren't verified by EasyMock; whereas andReturn() methods are verified.
Glide
That is correct.
Barend