I designed a webservice to perform a task if request parameters are OK, or return 401 Unauthorized HTTP status code if request parameters are wrong or empty.
I'm using RestTemplate
to perform a test and I'm able to verify the HTTP 200 OK status if the webservice replies with success. I am however unable to test for HTTP 401 error because RestTemplate
itself throws an exception.
My test method is
@Test
public void testUnauthorized()
{
Map<String, Object> params = new HashMap<String, Object>();
ResponseEntity response = restTemplate.postForEntity(url, params, Map.class);
Assert.assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
Assert.assertNotNull(response.getBody());
}
Exception log is
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:533)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:489)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:447)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:318)
How I can test if webservice replies with a HTTP status code 401?