EasyMock andReturn()与andStubReturn() [英] EasyMock andReturn() vs andStubReturn()

查看:188
本文介绍了EasyMock andReturn()与andStubReturn()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在EasyMock中使用 andReturn(T值) andStubReturn(T值)有什么区别? / p>

在哪种情况下,您将使用 andStubReturn()哪里 andReturn()无法达到相同的结果?

解决方案

您将存根返回值用于您希望发生但不感兴趣的模拟上的方法调用。您可以对常规方法调用使用常规返回。



请考虑以下方法:

  public void someMethod(String arg){
if(logger.isDebugEnabled()){
logger.debug(在服务上调用doSomething()
+服务.getName()。hashCode());
}

service.postMessage( { + arg +});

if(logger.isDebugEnabled()){
logger.info(在服务上调用doSomething()完成
+ service.getName()。hashCode());
}
}

...其中服务是一个可模拟的字段。 log语句中的 hashCode()是人为设计的,但要点是,您的模拟需要响应对 getName()的任意数量的调用避免使用NPE,而您可能会对此不太在意。



为此方法编写基于EasyMock的单元测试时, 'd andStubReturn()调用 getName()并使用普通的 andReturn() 调用 postMessage(String)。当您验证模拟对象时,它只会考虑后者,并且如果您更改log4j配置,测试也不会中断。


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?

解决方案

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.

这篇关于EasyMock andReturn()与andStubReturn()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆