From cfb7777a070ca2d19c91b98bf39c42bdf8d7be72 Mon Sep 17 00:00:00 2001 From: Rob Tompkins Date: Sun, 9 Sep 2018 20:31:07 -0400 Subject: [PATCH] Exception response for MockRestServiceServer Closes gh-1954 --- .../client/response/MockRestResponseCreators.java | 12 ++++++++++++ .../web/client/response/ResponseCreatorsTests.java | 8 ++++++++ 2 files changed, 20 insertions(+) diff --git a/spring-test/src/main/java/org/springframework/test/web/client/response/MockRestResponseCreators.java b/spring-test/src/main/java/org/springframework/test/web/client/response/MockRestResponseCreators.java index ceb7c028de..497f6b8276 100644 --- a/spring-test/src/main/java/org/springframework/test/web/client/response/MockRestResponseCreators.java +++ b/spring-test/src/main/java/org/springframework/test/web/client/response/MockRestResponseCreators.java @@ -16,6 +16,7 @@ package org.springframework.test.web.client.response; +import java.io.IOException; import java.net.URI; import org.springframework.core.io.Resource; @@ -116,4 +117,15 @@ public abstract class MockRestResponseCreators { return new DefaultResponseCreator(status); } + /** + * {@code ResponseCreator} with an internal application {@code IOException}. For example, + * one could use this to simulate a {@code SocketTimeoutException}. + * @param e the {@code Exception} to be thrown at HTTP call time. + */ + public static ResponseCreator withException(IOException e) { + return request -> { + throw e; + }; + } + } diff --git a/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java b/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java index 0465bdebd3..00dcb1aa04 100644 --- a/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java +++ b/spring-test/src/test/java/org/springframework/test/web/client/response/ResponseCreatorsTests.java @@ -16,6 +16,7 @@ package org.springframework.test.web.client.response; +import java.net.SocketTimeoutException; import java.net.URI; import org.junit.jupiter.api.Test; @@ -23,6 +24,7 @@ import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.mock.http.client.MockClientHttpResponse; +import org.springframework.test.web.client.ResponseCreator; import org.springframework.util.StreamUtils; import static org.assertj.core.api.Assertions.assertThat; @@ -124,4 +126,10 @@ public class ResponseCreatorsTests { assertThat(StreamUtils.copyToByteArray(response.getBody()).length).isEqualTo(0); } + @Test(expected = SocketTimeoutException.class) + public void withException() throws Exception { + ResponseCreator responseCreator = MockRestResponseCreators.withException(new SocketTimeoutException()); + responseCreator.createResponse(null); + } + }