Mockito Unit Test The case of a call is ambiguous (you need to make it not to be ambiguous)

How do I write the following Mockito Matchers so that the call is not ambiguous?

The actual function call I'm trying to make fun of in my code:

//Variables String url = http://theServer:8080/oath2-v1/token; HttpEntity<String> request = new HttpEntity<String>("name=value",headers); //Method call I am trying to mock using Mockito response=cmsRestTemplate.exchange(url, HttpMethod.POST, request, DdsOAuthToken.class); 

Below is a snippet from my Unit Test case. It contains the following simulated call, emulating the above call, but, unfortunately, the compiler considers it ambiguous and does not compile.

 //From the Unit Test... when(restTemplate.exchange( Matchers.anyString(), Matchers.any(HttpMethod.class), Matchers.any(HttpEntity.class), Matchers.<Class<DdsOAuthToken>>any(), Matchers.anyVararg()).thenReturn(response)); 

The error I am getting is as follows:

 The method exchange(String, HttpMethod, HttpEntity<?>, Class<DdsOAuthToken>, Object[]) is ambiguous for the type RestTemplate 

This is the Spring RestTemplate api call. In particular, two api calls that it finds ambiguous, the following two calls:

 1. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) 2. exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables) 

I'm trying to make fun of # 1 above. But the Java compiler cannot determine if I am trying to call No. 1 or No. 2. Exactly how should I write Mockito layouts so that it knows that I want # 1 higher and not # 2?

+5
source share
2 answers

You need to add cast (Object[]) to the vararg parameter. This may be relevant to the declaration of anyVararg method. But I'm not so sure about that. Therefore, your code should be:

 //From the Unit Test... when(restTemplate.exchange( Matchers.anyString(), Matchers.any(HttpMethod.class), Matchers.any(HttpEntity.class), Matchers.<Class<DdsOAuthToken>>any(), (Object[]) Matchers.anyVararg()).thenReturn(response)); 
+1
source

This is usually a bad decision to make fun of classes that you do not control. The Spring framework comes with useful classes to help you test the use of the framework.

For example, MockRestServiceServer is a dummy server that will give valid answers for the RestTemplate instance, so you don't have to mock it.

Documentation example

 RestTemplate restTemplate = new RestTemplate(); MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate); mockServer.expect(requestTo("/greeting")) .andRespond(withSuccess("Hello world", "text/plain")); // use RestTemplate ... 
0
source

All Articles