Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

unit testing - EasyMock andReturn() vs andStubReturn()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...