Polishing

This commit is contained in:
Juergen Hoeller
2016-08-09 12:12:42 +02:00
parent e8562bb3af
commit 6924f00f8c
12 changed files with 77 additions and 95 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request;
@@ -33,6 +34,7 @@ import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.util.Assert;
/**
* A {@link ClientHttpRequestFactory} for requests executed via {@link MockMvc}.
@@ -46,29 +48,26 @@ public class MockMvcClientHttpRequestFactory implements ClientHttpRequestFactory
public MockMvcClientHttpRequestFactory(MockMvc mockMvc) {
Assert.notNull(mockMvc, "MockMvc must not be null");
this.mockMvc = mockMvc;
}
public ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
return new MockClientHttpRequest(httpMethod, uri) {
@Override
public ClientHttpResponse executeInternal() throws IOException {
try {
MockHttpServletRequestBuilder requestBuilder = request(httpMethod, uri.toString());
requestBuilder.content(getBodyAsBytes());
requestBuilder.headers(getHeaders());
MvcResult mvcResult = MockMvcClientHttpRequestFactory.this.mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse servletResponse = mvcResult.getResponse();
HttpStatus status = HttpStatus.valueOf(servletResponse.getStatus());
byte[] body = servletResponse.getContentAsByteArray();
HttpHeaders headers = getResponseHeaders(servletResponse);
MockClientHttpResponse clientResponse = new MockClientHttpResponse(body, status);
clientResponse.getHeaders().putAll(headers);
return clientResponse;
}
catch (Exception ex) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,8 +28,7 @@ import org.springframework.http.client.ClientHttpRequest;
public interface RequestMatcher {
/**
* Match the given request against some expectations.
*
* Match the given request against specific expectations.
* @param request the request to make assertions on
* @throws IOException in case of I/O errors
* @throws AssertionError if expectations are not met

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -45,6 +45,7 @@ class RequestMatcherClientHttpRequest extends MockClientHttpRequest implements R
this.requestMatchers.add(requestMatcher);
}
public ResponseActions andExpect(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "RequestMatcher is required");
this.requestMatchers.add(requestMatcher);
@@ -57,22 +58,17 @@ class RequestMatcherClientHttpRequest extends MockClientHttpRequest implements R
}
public ClientHttpResponse executeInternal() throws IOException {
if (this.requestMatchers.isEmpty()) {
throw new AssertionError("No request expectations to execute");
}
if (this.responseCreator == null) {
throw new AssertionError("No ResponseCreator was set up. Add it after request expectations, "
+ "e.g. MockRestServiceServer.expect(requestTo(\"/foo\")).andRespond(withSuccess())");
throw new AssertionError("No ResponseCreator was set up. Add it after request expectations, " +
"e.g. MockRestServiceServer.expect(requestTo(\"/foo\")).andRespond(withSuccess())");
}
for (RequestMatcher requestMatcher : this.requestMatchers) {
requestMatcher.match(this);
}
setResponse(this.responseCreator.createResponse(this));
return super.executeInternal();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -52,6 +52,7 @@ public class ContentRequestMatchers {
this.xmlHelper = new XmlExpectationsHelper();
}
/**
* Assert the request content type as a String.
*/
@@ -135,10 +136,8 @@ public class ContentRequestMatchers {
* Parse the request body and the given String as XML and assert that the
* two are "similar" - i.e. they contain the same elements and attributes
* regardless of order.
*
* <p>Use of this matcher assumes the
* <a href="http://xmlunit.sourceforge.net/">XMLUnit<a/> library is available.
*
* @param expectedXmlContent the expected XML content
*/
public RequestMatcher xml(final String expectedXmlContent) {
@@ -175,6 +174,7 @@ public class ContentRequestMatchers {
};
}
/**
* Abstract base class for XML {@link RequestMatcher}'s.
*/
@@ -191,6 +191,6 @@ public class ContentRequestMatchers {
}
protected abstract void matchInternal(MockClientHttpRequest request) throws Exception;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,8 +25,8 @@ import org.springframework.test.util.JsonPathExpectationsHelper;
import org.springframework.test.web.client.RequestMatcher;
/**
* Factory methods for request content {@code RequestMatcher}'s using a <a
* href="http://goessner.net/articles/JsonPath/">JSONPath</a> expression.
* Factory methods for request content {@code RequestMatcher}'s using a
* <a href="http://goessner.net/articles/JsonPath/">JSONPath</a> expression.
* An instance of this class is typically accessed via
* {@code RequestMatchers.jsonPath(..)}.
*
@@ -42,7 +42,6 @@ public class JsonPathRequestMatchers {
* Class constructor, not for direct instantiation. Use
* {@link MockRestRequestMatchers#jsonPath(String, Matcher)} or
* {@link MockRestRequestMatchers#jsonPath(String, Object...)}.
*
* @param expression the JSONPath expression
* @param args arguments to parameterize the JSONPath expression with using
* the formatting specifiers defined in
@@ -123,12 +122,12 @@ public class JsonPathRequestMatchers {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
matchInternal(mockRequest);
}
catch (ParseException e) {
throw new AssertionError("Failed to parse JSON request content: " + e.getMessage());
catch (ParseException ex) {
throw new AssertionError("Failed to parse JSON request content: " + ex.getMessage());
}
}
protected abstract void matchInternal(MockClientHttpRequest request) throws IOException, ParseException;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,13 +47,6 @@ import org.springframework.util.Assert;
*/
public abstract class MockRestRequestMatchers {
/**
* Private class constructor.
*/
private MockRestRequestMatchers() {
}
/**
* Match to any request.
*/
@@ -66,7 +59,6 @@ public abstract class MockRestRequestMatchers {
/**
* Assert the request URI string with the given matcher.
*
* @param matcher String matcher for the expected URI
* @return the request matcher
*/
@@ -81,7 +73,6 @@ public abstract class MockRestRequestMatchers {
/**
* Assert the request URI string.
*
* @param expectedUri the expected URI
* @return the request matcher
*/
@@ -96,7 +87,6 @@ public abstract class MockRestRequestMatchers {
/**
* Assert the {@link HttpMethod} of the request.
*
* @param method the HTTP method
* @return the request matcher
*/
@@ -111,7 +101,6 @@ public abstract class MockRestRequestMatchers {
/**
* Expect a request to the given URI.
*
* @param uri the expected URI
* @return the request matcher
*/
@@ -156,8 +145,8 @@ public abstract class MockRestRequestMatchers {
private static void assertHeaderValueCount(final String name, HttpHeaders headers, int expectedCount) {
List<String> actualValues = headers.get(name);
AssertionErrors.assertTrue("Expected header <" + name + ">", actualValues != null);
AssertionErrors.assertTrue("Expected header <" + name + "> to have at least <" + expectedCount
+ "> values but found " + actualValues, expectedCount <= actualValues.size());
AssertionErrors.assertTrue("Expected header <" + name + "> to have at least <" + expectedCount +
"> values but found " + actualValues, expectedCount <= actualValues.size());
}
/**
@@ -168,12 +157,11 @@ public abstract class MockRestRequestMatchers {
}
/**
* Access to request body matchers using a <a
* href="http://goessner.net/articles/JsonPath/">JSONPath</a> expression to
* Access to request body matchers using a
* <a href="http://goessner.net/articles/JsonPath/">JSONPath</a> expression to
* inspect a specific subset of the body. The JSON path expression can be a
* parameterized string using formatting specifiers as defined in
* {@link String#format(String, Object...)}.
*
* @param expression the JSON path optionally parameterized with arguments
* @param args arguments to parameterize the JSON path expression with
*/
@@ -182,11 +170,10 @@ public abstract class MockRestRequestMatchers {
}
/**
* Access to request body matchers using a <a
* href="http://goessner.net/articles/JsonPath/">JSONPath</a> expression to
* Access to request body matchers using a
* <a href="http://goessner.net/articles/JsonPath/">JSONPath</a> expression to
* inspect a specific subset of the body and a Hamcrest match for asserting
* the value found at the JSON path.
*
* @param expression the JSON path expression
* @param matcher a matcher for the value expected at the JSON path
*/
@@ -199,7 +186,6 @@ public abstract class MockRestRequestMatchers {
* subset of the body. The XPath expression can be a parameterized string
* using formatting specifiers as defined in
* {@link String#format(String, Object...)}.
*
* @param expression the XPath optionally parameterized with arguments
* @param args arguments to parameterize the XPath expression with
*/
@@ -212,7 +198,6 @@ public abstract class MockRestRequestMatchers {
* subset of the body. The XPath expression can be a parameterized string
* using formatting specifiers as defined in
* {@link String#format(String, Object...)}.
*
* @param expression the XPath optionally parameterized with arguments
* @param namespaces namespaces referenced in the XPath expression
* @param args arguments to parameterize the XPath expression with

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.match;
import java.io.IOException;
@@ -44,12 +45,10 @@ public class XpathRequestMatchers {
* Class constructor, not for direct instantiation. Use
* {@link MockRestRequestMatchers#xpath(String, Object...)} or
* {@link MockRestRequestMatchers#xpath(String, Map, Object...)}.
*
* @param expression the XPath expression
* @param namespaces XML namespaces referenced in the XPath expression, or {@code null}
* @param args arguments to parameterize the XPath expression with using the
* formatting specifiers defined in {@link String#format(String, Object...)}
*
* @throws XPathExpressionException
*/
protected XpathRequestMatchers(String expression, Map<String, String> namespaces, Object ... args)
@@ -58,6 +57,7 @@ public class XpathRequestMatchers {
this.xpathHelper = new XpathExpectationsHelper(expression, namespaces, args);
}
/**
* Apply the XPath and assert it with the given {@code Matcher<Node>}.
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.test.web.client.response;
import java.io.IOException;
@@ -38,36 +39,24 @@ import org.springframework.util.Assert;
*/
public class DefaultResponseCreator implements ResponseCreator {
private HttpStatus statusCode;
private byte[] content;
private Resource contentResource;
private final HttpHeaders headers = new HttpHeaders();
private HttpStatus statusCode;
/**
* Protected constructor.
* Use static factory methods in {@link MockRestResponseCreators}.
*/
protected DefaultResponseCreator(HttpStatus statusCode) {
Assert.notNull(statusCode);
Assert.notNull(statusCode, "HttpStatus must not be null");
this.statusCode = statusCode;
}
public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException {
MockClientHttpResponse response;
if (this.contentResource != null ){
InputStream stream = this.contentResource.getInputStream();
response = new MockClientHttpResponse(stream, this.statusCode);
}
else {
response = new MockClientHttpResponse(this.content, this.statusCode);
}
response.getHeaders().putAll(this.headers);
return response;
}
/**
* Set the body as a UTF-8 String.
@@ -76,9 +65,9 @@ public class DefaultResponseCreator implements ResponseCreator {
try {
this.content = content.getBytes("UTF-8");
}
catch (UnsupportedEncodingException e) {
catch (UnsupportedEncodingException ex) {
// should not happen, UTF-8 is always supported
throw new IllegalStateException(e);
throw new IllegalStateException(ex);
}
return this;
}
@@ -129,4 +118,18 @@ public class DefaultResponseCreator implements ResponseCreator {
return this;
}
public ClientHttpResponse createResponse(ClientHttpRequest request) throws IOException {
MockClientHttpResponse response;
if (this.contentResource != null) {
InputStream stream = this.contentResource.getInputStream();
response = new MockClientHttpResponse(stream, this.statusCode);
}
else {
response = new MockClientHttpResponse(this.content, this.statusCode);
}
response.getHeaders().putAll(this.headers);
return response;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,10 +33,6 @@ import org.springframework.test.web.client.ResponseCreator;
*/
public abstract class MockRestResponseCreators {
private MockRestResponseCreators() {
}
/**
* {@code ResponseCreator} for a 200 response (OK).
*/

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.http;
import java.io.ByteArrayInputStream;
@@ -37,14 +38,15 @@ public class MockHttpInputMessage implements HttpInputMessage {
public MockHttpInputMessage(byte[] contents) {
this.body = (contents != null) ? new ByteArrayInputStream(contents) : null;
this.body = (contents != null ? new ByteArrayInputStream(contents) : null);
}
public MockHttpInputMessage(InputStream body) {
Assert.notNull(body, "'body' must not be null");
Assert.notNull(body, "InputStream must not be null");
this.body = body;
}
public HttpHeaders getHeaders() {
return this.headers;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,14 +33,14 @@ import org.springframework.mock.http.MockHttpOutputMessage;
*/
public class MockClientHttpRequest extends MockHttpOutputMessage implements ClientHttpRequest {
private URI uri;
private HttpMethod httpMethod;
private boolean executed = false;
private URI uri;
private ClientHttpResponse clientHttpResponse;
private boolean executed = false;
/**
* Default constructor.
@@ -56,20 +56,21 @@ public class MockClientHttpRequest extends MockHttpOutputMessage implements Clie
this.uri = uri;
}
public URI getURI() {
return this.uri;
}
public void setURI(URI uri) {
this.uri = uri;
public void setMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
}
public HttpMethod getMethod() {
return this.httpMethod;
}
public void setMethod(HttpMethod httpMethod) {
this.httpMethod = httpMethod;
public void setURI(URI uri) {
this.uri = uri;
}
public URI getURI() {
return this.uri;
}
public void setResponse(ClientHttpResponse clientHttpResponse) {
@@ -93,7 +94,6 @@ public class MockClientHttpRequest extends MockHttpOutputMessage implements Clie
/**
* The default implementation returns the configured
* {@link #setResponse(ClientHttpResponse) response}.
*
* <p>Override this method to execute the request and provide a response,
* potentially different than the configured response.
*/
@@ -101,6 +101,7 @@ public class MockClientHttpRequest extends MockHttpOutputMessage implements Clie
return this.clientHttpResponse;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@@ -111,7 +112,7 @@ public class MockClientHttpRequest extends MockHttpOutputMessage implements Clie
sb.append(" ").append(this.uri);
}
if (!getHeaders().isEmpty()) {
sb.append(", headers : ").append(getHeaders());
sb.append(", headers: ").append(getHeaders());
}
if (sb.length() == 0) {
sb.append("Not yet initialized");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.http.client;
import java.io.IOException;
@@ -39,7 +40,7 @@ public class MockClientHttpResponse extends MockHttpInputMessage implements Clie
*/
public MockClientHttpResponse(byte[] body, HttpStatus statusCode) {
super(body);
Assert.notNull(statusCode, "statisCode is required");
Assert.notNull(statusCode, "HttpStatus is required");
this.status = statusCode;
}
@@ -48,10 +49,11 @@ public class MockClientHttpResponse extends MockHttpInputMessage implements Clie
*/
public MockClientHttpResponse(InputStream body, HttpStatus statusCode) {
super(body);
Assert.notNull(statusCode, "statisCode is required");
Assert.notNull(statusCode, "HttpStatus is required");
this.status = statusCode;
}
public HttpStatus getStatusCode() throws IOException {
return this.status;
}