Mockito Matchers: matching a Class type in parameter list
Figured out.
The method being called was a parameterized method, but could not infer the parameter type from the matcher argument (the last argument was of type Class).
Making the explicit call
when(restTemplate.exchange(isA(URI.class), eq(POST), isA(HttpEntity.class), eq(Long.class)))
.thenThrow(new RestClientException(EXCEPTION_MESSAGE));
fixed my problem.
Related videos on Youtube
piper1970
Updated on September 15, 2022Comments
-
piper1970 over 1 year
I am working with Java, Spring's RestTemplate, and Mockito, using Eclipse. I am trying to mock Spring's rest template, and the last parameter for the method I am mocking is a Class type. Below is the signature for the function:
public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException
The initial attempt I made to mock this method is as follows:
//given restTemplate returns exception when(restTemplate.exchange(isA(URI.class), eq(HttpMethod.POST), isA(HttpEntity.class), eq(Long.class))).thenThrow(new RestClientException(EXCEPTION_MESSAGE));
However, this line of code produces the following error from eclipse:
The method exchange(URI, HttpMethod, HttpEntity<?>, Class<T>) in the type RestTemplate is not applicable for the arguments (URI, HttpMethod, HttpEntity, Class<Long>)
Eclipse then suggests I cast the last parameter with a 'Class' cast, but does not seem to work if I cast it to a 'Class', or other type.
I've been looking online for help on this, but seem to stumped on the fact that the parameter requested is a class type.
The answers I've looked at so far have been mainly related to generic collections. Any help here would be greatly appreciated.
-
GavinHave you checked that you haven't accidentally used a Hamcrest matcher rather than a mockito match, I have been caught out by that before, though usually with any.
-
-
Akshay about 2 yearsI am unable to figure out what is the fix. The stubbing in question and answer is exactly the same. Both have
eq(Long.class)
. What change in the stubbing code fixed the issue? -
piper1970 about 2 years@Akshay, it's been quite a while since I wrote this. I think from what was in the comments I put for the original question, I meant to call the exchange function with the parameterized version, such as
when(rest.<Long>exchange(...)).thenThrow(...)
. I'm not sure how that got left out, since the code in the answer definitely doesn't have anything changed in it. I hope this helps, and I apologize for the confusing post -
piper1970 about 2 years@Onema appears to have modified the answer that I posted originally. Not appreciated, since it basically reverted back to the original form
-
Onema about 2 yearsReverted, appologies
-
Anand Rockzz almost 2 yearscannot convert from Matcher<Object> to HttpEntity<?>