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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…