2013-10-18 32 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);