2013-10-18 31 views
2

我试图嘲弄Spring的MessageSource.getMessage方法,但Mockito它与无用信息抱怨,我使用:模拟Spring的MessageSource.getMessage方法

when(mockMessageSource.getMessage(anyString(), any(Object[].class), any(Locale.class))) 
    .thenReturn(anyString()); 

的错误信息是:

You cannot use argument matchers outside of verification or stubbing. 
Examples of correct usage of argument matchers: 

when(mock.get(anyInt())).thenReturn(null); 
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject()); 

verify(mock).someMethod(contains("foo")) 

Also, this error might show up because you use argument matchers with methods 
that cannot be mocked Following methods *cannot* be stubbed/verified: final/private/equals() 
/hashCode(). 

任何想法我做错了什么?

回答

3

我相信问题在于anyString()是它在您的thenReturn(...)调用中用作参数时所抱怨的匹配器。如果你不在乎返回的是什么,只需返回一个空字符串即可。

+1

谢谢,工作。 – user86834

1

的一件事看起来很奇怪对我说:

您正在返回Mockito.anyString()这是一个Matcher

我想你必须返回一个具体的字符串。

when(mockMessageSource.getMessage(anyString(), any(Object[].class), any(Locale.class))) 
.thenReturn("returnValue"); 
1

这里的问题是,你需要返回一些实际的对象匹配你的模拟方法的返回类型。 比较:

when(mockMessageSource.getMessage(anyString(), any(Object[].class), any(Locale.class))). 
thenReturn("A Value that I care about, or not"); 

更大的问题这点到是,你真的不测试任何行为。你可能想考虑这个测试提供的价值。为什么首先嘲笑对象?

1

尽管接受的答案对问题中的代码有修复,但我想指出,没有必要仅使用模拟库来创建始终返回空字符串的MessageSource

下面的代码做同样的:

MessageSource messageSource = new AbstractMessageSource() { 
    protected MessageFormat resolveCode(String code, Locale locale) { 
     return new MessageFormat(""); 
    } 
}; 
0

我只在从事间谍活动的MessageSource(所以我仍然可以稍后验证电话的getMessage)和标志“useCodeAsDefaultMessage”设置为true,解决了这个问题。 在这种情况下,来自AbstractMessageSource#getMessage的回退机制将完成其工作并仅将所提供的密钥作为消息返回。

messageSource = spy(new ReloadableResourceBundleMessageSource()); 
messageSource.setUseCodeAsDefaultMessage(true);