有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaMockSpring的消息源。getMessage方法

我试图模仿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().

知道我做错了什么吗


共 (6) 个答案

  1. # 1 楼答案

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

    messageSource = spy(new ReloadableResourceBundleMessageSource());
    messageSource.setUseCodeAsDefaultMessage(true);
    
  2. # 2 楼答案

    我认为问题在于anyString()是它在thenReturn(...)调用中用作参数时所抱怨的匹配器。如果不关心返回的内容,只需返回一个空字符串a thenReturn("")

  3. # 3 楼答案

    虽然已被接受的答案对问题中的代码有修复,但我想指出的是,不必使用模拟库来创建总是返回空字符串的MessageSource

    以下代码执行相同的操作:

    MessageSource messageSource = new AbstractMessageSource() {
        protected MessageFormat resolveCode(String code, Locale locale) {
            return new MessageFormat("");
        }
    };
    
  4. # 4 楼答案

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

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

    这指出了一个更大的问题,那就是你实际上没有测试任何行为。你可能想考虑这个测试提供了什么价值。首先为什么要嘲笑这个物体

  5. # 5 楼答案

    ResourceBundleMessageSource类上的getMessage方法是最终的

  6. # 6 楼答案

    有一件事我觉得很奇怪:

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

    我认为你必须归还一根混凝土线

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