Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous Mockito - 0 Matchers Expected, 1 Recorded (InvalidUseOfMatchersException)

i'm facing a very strange problem.

 URL = "/my/specific/url/";
 when(this.restHelperMock.post(
 eq(myEnum),
 eq(this.config.apiEndpoint() + URL),
 any(JSONObject.class))).thenReturn(new JSONObject(myDesiredJsonContent));

or even with contains

 URL = "/my/specific/url/";
 when(this.restHelperMock.post(
 eq(myEnum),
 contains(this.config.apiEndpoint() + URL),
 any(JSONObject.class))).thenReturn(new JSONObject(myDesiredJsonContent));

gives me

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
0 matchers expected, 1 recorded:

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

Even if I don't use RAW expressions.
Strangely if I change the contains method to:

URL = "/my/specific/url/";
 when(this.restHelperMock.post(
 eq(myEnum),
 contains(URL),
 any(JSONObject.class))).thenReturn(new JSONObject(myDesiredJsonContent));

omitting the endpoint, it works.

The Config and RestHelper are both mocked:

this.restHelperMock = mock(RESTHelper.class);
this.config = mock(MyConfiguration.class);

when(this.config.apiEndpoint()).thenReturn("http://host:port/api");

The URL with ApiEndpoint is equal to what I wanted to mock, even if it wouldn't be, I should get a NullpointerException, because of false mocking. But here I don't have any ideea.

Thank you for your answers.

like image 796
David Laci Avatar asked Oct 22 '15 09:10

David Laci


1 Answers

The problem seems to be that you are calling a mocked method this.config.apiEndpoint() during the eq ( ... ) invocation. Try to simple put the complete URL in there ( host:port/api/my/specific/url ) instead of calling another mock there, which might confuse Mockito, since it relies on internal states for the mocking.

To be quite honest, I am not that deep into Mockito that I could explain WHY this happens, but I'll probably try to debug into it one day ;-)

Edit: Strangely enough, I seem not to be able to reproduce it with a simpler testcase. There seems to be more here than meets the eye.

like image 112
Florian Schaetz Avatar answered Oct 19 '22 19:10

Florian Schaetz