Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock Spring's MessageSource.getMessage method

I'm trying to mock Spring's MessageSource.getMessage method but Mockito it is complaining with an unhelpful message, I am using:

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

The error message is:

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

Any idea what I am doing wrong?

like image 606
user86834 Avatar asked Dec 15 '22 05:12

user86834


1 Answers

While the accepted answer has the fix for the code in the question, I'd like to note that it is not necessary to use a mock library just to create a MessageSource that always returns an empty string.

The following code does the same:

MessageSource messageSource = new AbstractMessageSource() {
    protected MessageFormat resolveCode(String code, Locale locale) {
        return new MessageFormat("");
    }
};
like image 106
herman Avatar answered Dec 17 '22 19:12

herman