dev danke
2013-07-29 23:23:17 UTC
I'm having a little trouble with Mockito. I have a RestClient that wraps
Spring's RestTemplate. In a unit test of my RestClient's post() method, I
want to verify that it correctly handles a RestTemplate exception.
The problem is that my unit test doesn't trigger the mocked restTemplate to
throw an exception. I want restTemplate.exchange() to throw an exception,
but instead it just returns null.
Here's the RestClient method I'm testing:
public <T> T post(String url, Object toPost, Class<T> responseType,
Object... urlVariables)
{
try
{
HttpEntity requestEntity = new HttpEntity(toPost);
ResponseEntity<T> responseEntity = restTemplate.exchange(url,
HttpMethod.POST, requestEntity, responseType, urlVariables);
return responseEntity.getBody();
}
catch (RestClientException e)
{
return null;
}
}
Here's my unit test:
@Test
public void whenPostReceivesExceptionItReturnsNull()
{
when(restTemplate.exchange(anyString(), any(HttpMethod.class),
any(HttpEntity.class), any(Class.class),
any(Object[].class))).thenThrow(RestClientException.class);
Object responseBody = restClient.post("someUrl", new HashMap(),
String.class);
Assert.assertNull(responseBody);
}
Here's the signature of the RestTemplate method I want to throw an
exception:
public <T> ResponseEntity<T> exchange(String url, HttpMethod
method, HttpEntity<?> requestEntity, Class<T> responseType, Object...
uriVariables)
throws RestClientException { ... }
Please let me know if you have any ideas on how to make this work.
Thanks,
Dan
Spring's RestTemplate. In a unit test of my RestClient's post() method, I
want to verify that it correctly handles a RestTemplate exception.
The problem is that my unit test doesn't trigger the mocked restTemplate to
throw an exception. I want restTemplate.exchange() to throw an exception,
but instead it just returns null.
Here's the RestClient method I'm testing:
public <T> T post(String url, Object toPost, Class<T> responseType,
Object... urlVariables)
{
try
{
HttpEntity requestEntity = new HttpEntity(toPost);
ResponseEntity<T> responseEntity = restTemplate.exchange(url,
HttpMethod.POST, requestEntity, responseType, urlVariables);
return responseEntity.getBody();
}
catch (RestClientException e)
{
return null;
}
}
Here's my unit test:
@Test
public void whenPostReceivesExceptionItReturnsNull()
{
when(restTemplate.exchange(anyString(), any(HttpMethod.class),
any(HttpEntity.class), any(Class.class),
any(Object[].class))).thenThrow(RestClientException.class);
Object responseBody = restClient.post("someUrl", new HashMap(),
String.class);
Assert.assertNull(responseBody);
}
Here's the signature of the RestTemplate method I want to throw an
exception:
public <T> ResponseEntity<T> exchange(String url, HttpMethod
method, HttpEntity<?> requestEntity, Class<T> responseType, Object...
uriVariables)
throws RestClientException { ... }
Please let me know if you have any ideas on how to make this work.
Thanks,
Dan