4

我正在尝试模拟 Spring 的MessageSource.getMessage方法,但Mockito它抱怨一条无用的消息,我正在使用:

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().

知道我做错了什么吗?

4

7 回答 7

3

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

于 2013-10-18T19:00:03.017 回答
3

虽然接受的答案对问题中的代码进行了修复,但我想指出,不必使用模拟库来创建MessageSource始终返回空字符串的 a 。

下面的代码做同样的事情:

MessageSource messageSource = new AbstractMessageSource() {
    protected MessageFormat resolveCode(String code, Locale locale) {
        return new MessageFormat("");
    }
};
于 2016-08-18T17:15:25.280 回答
2

好吧,我觉得有一件事很奇怪:

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

我认为您必须返回一个具体的字符串。

when(mockMessageSource.getMessage(anyString(), any(Object[].class), any(Locale.class)))
.thenReturn("returnValue");
于 2013-10-18T19:00:27.037 回答
1

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

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

这指向的更大问题是您实际上没有测试任何行为。您可能需要考虑此测试提供的价值。为什么首先要模拟对象?

于 2013-10-18T19:03:08.060 回答
1

我通过仅监视 MessageSource(因此我仍然可以稍后验证 getMessage 调用)并将标志“ useCodeAsDefaultMessage”设置为 true 来解决了这个问题。在这种情况下,来自 的后备机制AbstractMessageSource#getMessage将完成其工作,并将提供的密钥作为消息返回。

messageSource = spy(new ReloadableResourceBundleMessageSource());
messageSource.setUseCodeAsDefaultMessage(true);
于 2017-08-07T10:22:57.080 回答
1

类 ResourceBundleMessageSource 上的 getMessage 方法是最终的

于 2019-05-01T06:25:07.623 回答
1
Mockito.when(messageSource.getMessage(Mockito.anyString(), Mockito.any(),Mockito.any(Locale.class))).thenReturn("Error Message");

这会帮助你

于 2020-03-03T13:25:41.367 回答