How to test a RestClientException with MockRestServiceServer

后端 未结 4 2278
不思量自难忘°
不思量自难忘° 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 04:57

    You can test throwing runtime exceptions from the MockRestServiceServer, although this class, as of Spring 5.0.0.RC4, is not designed for it (which means it may not work for more complex use cases):

    RestTemplate yourApi;
    MockRestServiceServer server = MockRestServiceServer.createServer(yourApi);
    
    server.expect(requestTo("http://..."))
        .andRespond((response) -> { throw new ResourceAccessException(
            new ConnectException("Connection reset")); });
    

    It seems to work in tests:

    • where there's only one RestTemplate call,
    • where the exception is thrown as a result of the last expectation.

    I wasn't able to expect two consecutive exceptions; the MockRestSeriviceServer (more concrete, the SimpleRequestExpectationManager) throws IllegalStateException on replaying the second expectation.

提交回复
热议问题