How to test a RestClientException with MockRestServiceServer

后端 未结 4 2277
不思量自难忘°
不思量自难忘° 2021-02-19 04:13

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:

4条回答
  •  一个人的身影
    2021-02-19 05:03

    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

提交回复
热议问题