Search code examples
javaspringmockingmockserver

How to test a RestClientException with MockRestServiceServer


While testing a RestClient-Implementation I want to simulate a RestClientException that may be thrown by some RestTemplate-methods in that implementation f.e. the delete-method:

@Override
public ResponseEntity<MyResponseModel> documentDelete(String id) {
    template.setErrorHandler(new MyResponseErrorHandler());
    ResponseEntity<MyResponseModel> response = null;
    try {
        String url = baseUrl + "/document/id/{id}";
        response = template.exchange(url, DELETE, null, MyResponseModel.class, id);
    } catch (RestClientException ex) {
        return handleException(ex);
    }
    return response;
}

How can I achieve this?

I define the mock-server in this way:

@Before
public void setUp() {
    mockServer = MockRestServiceServer.createServer(template);
    client = new MyRestClient(template, serverUrl + ":" + serverPort);
}

Solution

  • You can take advantage of the MockRestResponseCreators for mocking 4xx or 5xx responses from the mockRestServiceServer.

    For example for testing a 5xx - Internal server error:

    mockServer.expect(requestTo("your.url"))
                    .andExpect(method(HttpMethod.GET/POST....))
                    .andRespond(withServerError()...);
    

    In your case the RestClientException is thrown for client-side HTTP errors, so the example above can be fine tuned for a 4xx exception by using: ...andRespond(withBadRequest()); or ...andRespond(withStatus(HttpStatus.NOT_FOUND));

    For a more simpler usage of these methods you use static imports for org.springframework.test.web.client.MockRestServiceServer,org.springframework.test.web.client.response.MockRestResponseCreators