You need to implement ResponseErrorHandler in order to intercept response code, body, and header when you get non-2xx response codes from the service using rest template. Copy all the information you need, attach it to your custom exception and throw it so that you can catch it in your test.
public class CustomResponseErrorHandler implements ResponseErrorHandler {
private ResponseErrorHandler errorHandler = new DefaultResponseErrorHandler();
public boolean hasError(ClientHttpResponse response) throws IOException {
return errorHandler.hasError(response);
}
public void handleError(ClientHttpResponse response) throws IOException {
String theString = IOUtils.toString(response.getBody());
CustomException exception = new CustomException();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("code", response.getStatusCode().toString());
properties.put("body", theString);
properties.put("header", response.getHeaders());
exception.setProperties(properties);
throw exception;
}
}
Now what you need to do in your test is, set this ResponseErrorHandler in RestTemplate like,
RestTemplate restclient = new RestTemplate();
restclient.setErrorHandler(new CustomResponseErrorHandler());
try {
POJO pojo = restclient.getForObject(url, POJO.class);
} catch (CustomException e) {
Assert.isTrue(e.getProperties().get("body")
.equals("bad response"));
Assert.isTrue(e.getProperties().get("code").equals("400"));
Assert.isTrue(((HttpHeaders) e.getProperties().get("header"))
.get("fancyheader").toString().equals("[nilesh]"));
}