Browse Source

Move requests.add(request) into finally block.

This avoids "IllegalStateException: Expectations already declared" when
a MockRestServiceServer is used after one request throws an exception.

Issues: SPR-16132
pull/1580/head
Eric Pabst 7 years ago
parent
commit
43d88e4a25
  1. 9
      spring-test/src/main/java/org/springframework/test/web/client/AbstractRequestExpectationManager.java
  2. 19
      spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java

9
spring-test/src/main/java/org/springframework/test/web/client/AbstractRequestExpectationManager.java

@ -80,9 +80,12 @@ public abstract class AbstractRequestExpectationManager implements RequestExpect @@ -80,9 +80,12 @@ public abstract class AbstractRequestExpectationManager implements RequestExpect
if (requests.isEmpty()) {
afterExpectationsDeclared();
}
ClientHttpResponse response = validateRequestInternal(request);
requests.add(request);
return response;
try {
return validateRequestInternal(request);
}
finally {
requests.add(request);
}
}
}

19
spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java

@ -16,6 +16,7 @@ @@ -16,6 +16,7 @@
package org.springframework.test.web.client;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
@ -30,6 +31,7 @@ import org.springframework.mock.http.client.MockClientHttpRequest; @@ -30,6 +31,7 @@ import org.springframework.mock.http.client.MockClientHttpRequest;
import static org.junit.Assert.assertEquals;
import static org.springframework.http.HttpMethod.GET;
import static org.springframework.http.HttpMethod.POST;
import static org.springframework.test.util.AssertionErrors.fail;
import static org.springframework.test.web.client.ExpectedCount.max;
import static org.springframework.test.web.client.ExpectedCount.min;
import static org.springframework.test.web.client.ExpectedCount.once;
@ -184,6 +186,23 @@ public class SimpleRequestExpectationManagerTests { @@ -184,6 +186,23 @@ public class SimpleRequestExpectationManagerTests {
this.manager.validateRequest(createRequest(GET, "/bar"));
}
@Test // SPR-16132
public void sequentialRequestsWithFirstFailing() throws Exception {
this.manager.expectRequest(once(), requestTo("/foo")).andExpect(method(GET))
.andRespond(request -> { throw new SocketException("pseudo network error"); });
this.manager.expectRequest(once(), requestTo("/handle-error")).andExpect(method(POST)).andRespond(withSuccess());
try {
this.manager.validateRequest(createRequest(GET, "/foo"));
fail("expected exception");
}
catch (SocketException e) {
//expected
}
this.manager.validateRequest(createRequest(POST, "/handle-error"));
this.manager.verify();
}
private ClientHttpRequest createRequest(HttpMethod method, String url) {
try {

Loading…
Cancel
Save