Remove dependency on hamcrest-lib from spring-mvc-test

The change removes the use of concrete Matcher implementations and thus
the dependency on hamcrest-lib leaving hamcrest-core as the only
(optional) hamcrest dependency.

Issue: SPR-9961
This commit is contained in:
Rossen Stoyanchev 2012-11-07 17:01:11 -05:00
parent 9a6ec1b4b5
commit 4812fcccc4
18 changed files with 311 additions and 147 deletions

View File

@ -558,7 +558,6 @@ project('spring-test-mvc') {
compile project(":spring-test").sourceSets.main.output
compile("org.apache.tomcat:tomcat-servlet-api:7.0.8", provided)
compile("org.hamcrest:hamcrest-core:1.3", optional)
compile("org.hamcrest:hamcrest-library:1.3", optional)
compile("com.jayway.jsonpath:json-path:0.8.1", optional)
compile("xmlunit:xmlunit:1.2", optional)
testCompile("org.slf4j:jcl-over-slf4j:1.6.1")

View File

@ -16,14 +16,14 @@
package org.springframework.test.util;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.AssertionErrors.assertTrue;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import java.text.ParseException;
import java.util.List;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
@ -55,11 +55,13 @@ public class JsonPathExpectationsHelper {
/**
* Evaluate the JSONPath and assert the resulting value with the given {@code Matcher}.
* @param content the response content
* @param matcher the matcher to assert on the resulting json path
*/
@SuppressWarnings("unchecked")
public <T> void assertValue(String content, Matcher<T> matcher) throws ParseException {
T value = (T) evaluateJsonPath(content);
assertThat("JSON path: " + this.expression, value, matcher);
assertThat("JSON path" + this.expression, value, matcher);
}
private Object evaluateJsonPath(String content) throws ParseException {
@ -81,8 +83,19 @@ public class JsonPathExpectationsHelper {
/**
* Apply the JSONPath and assert the resulting value.
*/
public void assertValue(Object value) throws ParseException {
assertValue(Matchers.equalTo(value));
public void assertValue(String responseContent, Object expectedValue) throws ParseException {
Object actualValue = evaluateJsonPath(responseContent);
assertEquals("JSON path" + this.expression, expectedValue, actualValue);
}
/**
* Apply the JSONPath and assert the resulting value is an array.
*/
public void assertValueIsArray(String responseContent) throws ParseException {
Object actualValue = evaluateJsonPath(responseContent);
assertTrue("No value for JSON path " + this.expression, actualValue != null);
String reason = "Expected array at JSON path " + this.expression + " but found " + actualValue;
assertTrue(reason, actualValue instanceof List);
}
/**
@ -90,7 +103,7 @@ public class JsonPathExpectationsHelper {
*/
public void exists(String content) throws ParseException {
Object value = evaluateJsonPath(content);
String reason = "No value for JSON path: " + this.expression;
String reason = "No value for JSON path " + this.expression;
assertTrue(reason, value != null);
if (List.class.isInstance(value)) {
assertTrue(reason, !((List<?>) value).isEmpty());
@ -101,7 +114,6 @@ public class JsonPathExpectationsHelper {
* Evaluate the JSON path and assert it doesn't point to any content.
*/
public void doesNotExist(String content) throws ParseException {
Object value;
try {
value = evaluateJsonPath(content);
@ -109,7 +121,6 @@ public class JsonPathExpectationsHelper {
catch (AssertionError ex) {
return;
}
String reason = String.format("Expected no value for JSON path: %s but found: %s", this.expression, value);
if (List.class.isInstance(value)) {
assertTrue(reason, ((List<?>) value).isEmpty());
@ -118,5 +129,4 @@ public class JsonPathExpectationsHelper {
assertTrue(reason, value == null);
}
}
}

View File

@ -16,8 +16,8 @@
package org.springframework.test.util;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import static org.springframework.test.util.AssertionErrors.*;
import static org.springframework.test.util.MatcherAssertionErrors.*;
import java.io.StringReader;
import java.util.Collections;
@ -33,7 +33,6 @@ import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.util.xml.SimpleNamespaceContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
@ -93,7 +92,7 @@ public class XpathExpectationsHelper {
public void assertNode(String content, final Matcher<? super Node> matcher) throws Exception {
Document document = parseXmlString(content);
Node node = evaluateXpath(document, XPathConstants.NODE, Node.class);
assertThat("Xpath: " + XpathExpectationsHelper.this.expression, node, matcher);
assertThat("XPath " + this.expression, node, matcher);
}
/**
@ -128,7 +127,9 @@ public class XpathExpectationsHelper {
* @throws Exception if content parsing or expression evaluation fails
*/
public void exists(String content) throws Exception {
assertNode(content, Matchers.notNullValue());
Document document = parseXmlString(content);
Node node = evaluateXpath(document, XPathConstants.NODE, Node.class);
assertTrue("XPath " + this.expression + " does not exist", node != null);
}
/**
@ -136,7 +137,9 @@ public class XpathExpectationsHelper {
* @throws Exception if content parsing or expression evaluation fails
*/
public void doesNotExist(String content) throws Exception {
assertNode(content, Matchers.nullValue());
Document document = parseXmlString(content);
Node node = evaluateXpath(document, XPathConstants.NODE, Node.class);
assertTrue("XPath " + this.expression + " exists", node == null);
}
/**
@ -148,8 +151,7 @@ public class XpathExpectationsHelper {
public void assertNodeCount(String content, Matcher<Integer> matcher) throws Exception {
Document document = parseXmlString(content);
NodeList nodeList = evaluateXpath(document, XPathConstants.NODESET, NodeList.class);
String reason = "nodeCount Xpath: " + XpathExpectationsHelper.this.expression;
assertThat(reason, nodeList.getLength(), matcher);
assertThat("nodeCount for XPath " + this.expression, nodeList.getLength(), matcher);
}
/**
@ -157,7 +159,9 @@ public class XpathExpectationsHelper {
* @throws Exception if content parsing or expression evaluation fails
*/
public void assertNodeCount(String content, int expectedCount) throws Exception {
assertNodeCount(content, Matchers.equalTo(expectedCount));
Document document = parseXmlString(content);
NodeList nodeList = evaluateXpath(document, XPathConstants.NODESET, NodeList.class);
assertEquals("nodeCount for XPath " + this.expression, expectedCount, nodeList.getLength());
}
/**
@ -169,7 +173,7 @@ public class XpathExpectationsHelper {
public void assertString(String content, Matcher<? super String> matcher) throws Exception {
Document document = parseXmlString(content);
String result = evaluateXpath(document, XPathConstants.STRING, String.class);
assertThat("Xpath: " + XpathExpectationsHelper.this.expression, result, matcher);
assertThat("XPath " + this.expression, result, matcher);
}
/**
@ -177,7 +181,9 @@ public class XpathExpectationsHelper {
* @throws Exception if content parsing or expression evaluation fails
*/
public void assertString(String content, String expectedValue) throws Exception {
assertString(content, Matchers.equalTo(expectedValue));
Document document = parseXmlString(content);
String actual = evaluateXpath(document, XPathConstants.STRING, String.class);
assertEquals("XPath " + this.expression, expectedValue, actual);
}
/**
@ -189,7 +195,7 @@ public class XpathExpectationsHelper {
public void assertNumber(String content, Matcher<? super Double> matcher) throws Exception {
Document document = parseXmlString(content);
Double result = evaluateXpath(document, XPathConstants.NUMBER, Double.class);
assertThat("Xpath: " + XpathExpectationsHelper.this.expression, result, matcher);
assertThat("XPath " + this.expression, result, matcher);
}
/**
@ -197,7 +203,9 @@ public class XpathExpectationsHelper {
* @throws Exception if content parsing or expression evaluation fails
*/
public void assertNumber(String content, Double expectedValue) throws Exception {
assertNumber(content, Matchers.equalTo(expectedValue));
Document document = parseXmlString(content);
Double actual = evaluateXpath(document, XPathConstants.NUMBER, Double.class);
assertEquals("XPath " + this.expression, expectedValue, actual);
}
/**
@ -206,8 +214,8 @@ public class XpathExpectationsHelper {
*/
public void assertBoolean(String content, boolean expectedValue) throws Exception {
Document document = parseXmlString(content);
String result = evaluateXpath(document, XPathConstants.STRING, String.class);
assertEquals("Xpath:", expectedValue, Boolean.parseBoolean(result));
String actual = evaluateXpath(document, XPathConstants.STRING, String.class);
assertEquals("XPath " + this.expression, expectedValue, Boolean.parseBoolean(actual));
}
}

View File

@ -25,7 +25,6 @@ import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpRequest;
@ -88,8 +87,13 @@ public class ContentRequestMatchers {
/**
* Get the body of the request as a UTF-8 string and compare it to the given String.
*/
public RequestMatcher string(String expectedContent) {
return string(Matchers.equalTo(expectedContent));
public RequestMatcher string(final String expectedContent) {
return new RequestMatcher() {
public void match(ClientHttpRequest request) throws IOException, AssertionError {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
assertEquals("Request content", expectedContent, mockRequest.getBodyAsString());
}
};
}
/**
@ -99,8 +103,7 @@ public class ContentRequestMatchers {
return new RequestMatcher() {
public void match(ClientHttpRequest request) throws IOException, AssertionError {
MockClientHttpRequest mockRequest = (MockClientHttpRequest) request;
byte[] content = mockRequest.getBodyAsBytes();
assertThat("Request content", content, Matchers.equalTo(expectedContent));
assertEquals("Request content", expectedContent, mockRequest.getBodyAsBytes());
}
};
}

View File

@ -15,12 +15,8 @@
*/
package org.springframework.test.web.client.match;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import org.hamcrest.Matcher;
import org.springframework.http.client.ClientHttpRequest;
@ -71,8 +67,13 @@ public class JsonPathRequestMatchers {
/**
* Apply the JSONPath and assert the resulting value.
*/
public RequestMatcher value(Object expectedValue) {
return value(equalTo(expectedValue));
public RequestMatcher value(final Object expectedValue) {
return new AbstractJsonPathRequestMatcher() {
@Override
protected void matchInternal(MockClientHttpRequest request) throws IOException, ParseException {
jsonPathHelper.assertValue(request.getBodyAsString(), expectedValue);
}
};
}
/**
@ -103,7 +104,12 @@ public class JsonPathRequestMatchers {
* Assert the content at the given JSONPath is an array.
*/
public RequestMatcher isArray() {
return value(instanceOf(List.class));
return new AbstractJsonPathRequestMatcher() {
@Override
protected void matchInternal(MockClientHttpRequest request) throws IOException, ParseException {
jsonPathHelper.assertValueIsArray(request.getBodyAsString());
}
};
}

View File

@ -16,6 +16,7 @@
package org.springframework.test.web.client.match;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import static org.springframework.test.util.AssertionErrors.*;
import java.io.IOException;
import java.net.URI;
@ -25,8 +26,6 @@ import java.util.Map;
import javax.xml.xpath.XPathExpressionException;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.hamcrest.core.IsEqual;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
@ -83,12 +82,16 @@ public abstract class MockRestRequestMatchers {
/**
* Assert the request URI string.
*
* @param uri the expected URI
* @param expectedUri the expected URI
* @return the request matcher
*/
public static RequestMatcher requestTo(String uri) {
Assert.notNull(uri, "'uri' must not be null");
return requestTo(Matchers.equalTo(uri));
public static RequestMatcher requestTo(final String expectedUri) {
Assert.notNull(expectedUri, "'uri' must not be null");
return new RequestMatcher() {
public void match(ClientHttpRequest request) throws IOException, AssertionError {
assertEquals("Request URI", expectedUri, request.getURI().toString());
}
};
}
/**
@ -127,13 +130,9 @@ public abstract class MockRestRequestMatchers {
public static RequestMatcher header(final String name, final Matcher<? super String>... matchers) {
return new RequestMatcher() {
public void match(ClientHttpRequest request) {
HttpHeaders headers = request.getHeaders();
List<String> values = headers.get(name);
AssertionErrors.assertTrue("Expected header <" + name + ">", values != null);
AssertionErrors.assertTrue("Expected header <" + name + "> to have at least <" + matchers.length
+ "> values but it has only <" + values.size() + ">", matchers.length <= values.size());
assertHeaderValueCount(name, request.getHeaders(), matchers.length);
for (int i = 0 ; i < matchers.length; i++) {
assertThat("Request header", headers.get(name).get(i), matchers[i]);
assertThat("Request header", request.getHeaders().get(name).get(i), matchers[i]);
}
}
};
@ -142,13 +141,23 @@ public abstract class MockRestRequestMatchers {
/**
* Assert request header values.
*/
public static RequestMatcher header(String name, String... values) {
@SuppressWarnings("unchecked")
Matcher<? super String>[] matchers = new IsEqual[values.length];
for (int i = 0; i < values.length; i++) {
matchers[i] = Matchers.equalTo(values[i]);
}
return header(name, matchers);
public static RequestMatcher header(final String name, final String... expectedValues) {
return new RequestMatcher() {
public void match(ClientHttpRequest request) {
assertHeaderValueCount(name, request.getHeaders(), expectedValues.length);
for (int i = 0 ; i < expectedValues.length; i++) {
assertEquals("Request header + [" + name + "]",
expectedValues[i], request.getHeaders().get(name).get(i));
}
}
};
}
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());
}
/**

View File

@ -21,7 +21,6 @@ import java.util.Map;
import javax.xml.xpath.XPathExpressionException;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.mock.http.client.MockClientHttpRequest;
import org.springframework.test.util.XpathExpectationsHelper;
@ -75,14 +74,24 @@ public class XpathRequestMatchers {
* Assert that content exists at the given XPath.
*/
public <T> RequestMatcher exists() {
return node(Matchers.notNullValue());
return new AbstractXpathRequestMatcher() {
@Override
protected void matchInternal(MockClientHttpRequest request) throws Exception {
xpathHelper.exists(request.getBodyAsString());
}
};
}
/**
* Assert that content does not exist at the given XPath.
*/
public <T> RequestMatcher doesNotExist() {
return node(Matchers.nullValue());
return new AbstractXpathRequestMatcher() {
@Override
protected void matchInternal(MockClientHttpRequest request) throws Exception {
xpathHelper.doesNotExist(request.getBodyAsString());
}
};
}
/**
@ -101,8 +110,13 @@ public class XpathRequestMatchers {
/**
* Apply the XPath and assert the number of nodes found.
*/
public <T> RequestMatcher nodeCount(int expectedCount) {
return nodeCount(Matchers.equalTo(expectedCount));
public <T> RequestMatcher nodeCount(final int expectedCount) {
return new AbstractXpathRequestMatcher() {
@Override
protected void matchInternal(MockClientHttpRequest request) throws Exception {
xpathHelper.assertNodeCount(request.getBodyAsString(), expectedCount);
}
};
}
/**
@ -120,8 +134,13 @@ public class XpathRequestMatchers {
/**
* Apply the XPath and assert the String content found.
*/
public RequestMatcher string(String value) {
return string(Matchers.equalTo(value));
public RequestMatcher string(final String value) {
return new AbstractXpathRequestMatcher() {
@Override
protected void matchInternal(MockClientHttpRequest request) throws Exception {
xpathHelper.assertString(request.getBodyAsString(), value);
}
};
}
/**
@ -139,8 +158,13 @@ public class XpathRequestMatchers {
/**
* Apply the XPath and assert the number of nodes found.
*/
public RequestMatcher number(Double value) {
return number(Matchers.equalTo(value));
public RequestMatcher number(final Double value) {
return new AbstractXpathRequestMatcher() {
@Override
protected void matchInternal(MockClientHttpRequest request) throws Exception {
xpathHelper.assertNumber(request.getBodyAsString(), value);
}
};
}
/**

View File

@ -27,7 +27,6 @@ import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.http.MediaType;
import org.springframework.test.util.XmlExpectationsHelper;
import org.springframework.test.web.servlet.MvcResult;
@ -105,8 +104,12 @@ public class ContentResultMatchers {
/**
* Assert the response body content as a String.
*/
public ResultMatcher string(String content) {
return string(Matchers.equalTo(content));
public ResultMatcher string(final String expectedContent) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
assertEquals("Response content", expectedContent, result.getResponse().getContentAsString());
}
};
}
/**
@ -115,8 +118,7 @@ public class ContentResultMatchers {
public ResultMatcher bytes(final byte[] expectedContent) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
byte[] content = result.getResponse().getContentAsByteArray();
assertThat("Response content", content, Matchers.equalTo(expectedContent));
assertEquals("Response content", expectedContent, result.getResponse().getContentAsByteArray());
}
};
}

View File

@ -23,7 +23,6 @@ import static org.springframework.test.util.AssertionErrors.assertTrue;
import javax.servlet.http.Cookie;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
@ -61,8 +60,14 @@ public class CookieResultMatchers {
/**
* Assert a cookie value.
*/
public ResultMatcher value(String name, String value) {
return value(name, Matchers.equalTo(value));
public ResultMatcher value(final String name, final String expectedValue) {
return new ResultMatcher() {
public void match(MvcResult result) {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("Response cookie not found: " + name, cookie != null);
assertEquals("Response cookie", expectedValue, cookie.getValue());
}
};
}
/**
@ -107,8 +112,14 @@ public class CookieResultMatchers {
/**
* Assert a cookie's maxAge value.
*/
public ResultMatcher maxAge(String name, int maxAge) {
return maxAge(name, Matchers.equalTo(maxAge));
public ResultMatcher maxAge(final String name, final int maxAge) {
return new ResultMatcher() {
public void match(MvcResult result) {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("No cookie with name: " + name, cookie != null);
assertEquals("Response cookie maxAge", maxAge, cookie.getMaxAge());
}
};
}
/**
@ -123,8 +134,13 @@ public class CookieResultMatchers {
};
}
public ResultMatcher path(String name, String path) {
return path(name, Matchers.equalTo(path));
public ResultMatcher path(final String name, final String path) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie path", path, cookie.getPath());
}
};
}
/**
@ -142,8 +158,13 @@ public class CookieResultMatchers {
/**
* Assert a cookie's domain value.
*/
public ResultMatcher domain(String name, String domain) {
return domain(name, Matchers.equalTo(domain));
public ResultMatcher domain(final String name, final String domain) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie domain", domain, cookie.getDomain());
}
};
}
/**
@ -161,8 +182,13 @@ public class CookieResultMatchers {
/**
* Assert a cookie's comment value.
*/
public ResultMatcher comment(String name, String comment) {
return comment(name, Matchers.equalTo(comment));
public ResultMatcher comment(final String name, final String comment) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie comment", comment, cookie.getComment());
}
};
}
/**
@ -180,8 +206,13 @@ public class CookieResultMatchers {
/**
* Assert a cookie's version value.
*/
public ResultMatcher version(String name, int version) {
return version(name, Matchers.equalTo(version));
public ResultMatcher version(final String name, final int version) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie version", version, cookie.getVersion());
}
};
}
/**

View File

@ -16,11 +16,10 @@
package org.springframework.test.web.servlet.result;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.AssertionErrors.*;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
@ -57,7 +56,12 @@ public class FlashAttributeResultMatchers {
* Assert a flash attribute's value.
*/
public <T> ResultMatcher attribute(final String name, final Object value) {
return attribute(name, Matchers.equalTo(value));
return new ResultMatcher() {
@SuppressWarnings("unchecked")
public void match(MvcResult result) throws Exception {
assertEquals("Flash attribute", value, (T) result.getFlashMap().get(name));
}
};
}
/**
@ -67,7 +71,7 @@ public class FlashAttributeResultMatchers {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
for (String name : names) {
attribute(name, Matchers.notNullValue()).match(result);
assertTrue("Flash attribute [" + name + "] does not exist", result.getFlashMap().get(name) != null);
}
}
};

View File

@ -23,7 +23,6 @@ import static org.springframework.test.util.AssertionErrors.assertTrue;
import java.lang.reflect.Method;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.util.ClassUtils;
@ -75,9 +74,7 @@ public class HandlerResultMatchers {
public ResultMatcher methodName(final Matcher<? super String> matcher) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
Object handler = result.getHandler();
assertTrue("No handler: ", handler != null);
assertTrue("Not a HandlerMethod: " + handler, HandlerMethod.class.isInstance(handler));
Object handler = assertHandlerMethod(result);
assertThat("HandlerMethod", ((HandlerMethod) handler).getMethod().getName(), matcher);
}
};
@ -90,7 +87,12 @@ public class HandlerResultMatchers {
* {@link RequestMappingHandlerMapping} and {@link RequestMappingHandlerAdapter}.
*/
public ResultMatcher methodName(final String name) {
return methodName(Matchers.equalTo(name));
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
Object handler = assertHandlerMethod(result);
assertEquals("HandlerMethod", name, ((HandlerMethod) handler).getMethod().getName());
}
};
}
/**
@ -102,12 +104,17 @@ public class HandlerResultMatchers {
public ResultMatcher method(final Method method) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
Object handler = result.getHandler();
assertTrue("No handler: ", handler != null);
assertTrue("Not a HandlerMethod: " + handler, HandlerMethod.class.isInstance(handler));
Object handler = assertHandlerMethod(result);
assertEquals("HandlerMethod", method, ((HandlerMethod) handler).getMethod());
}
};
}
private static Object assertHandlerMethod(MvcResult result) {
Object handler = result.getHandler();
assertTrue("No handler: ", handler != null);
assertTrue("Not a HandlerMethod: " + handler, HandlerMethod.class.isInstance(handler));
return handler;
}
}

View File

@ -20,7 +20,6 @@ import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
@ -56,7 +55,11 @@ public class HeaderResultMatchers {
* Assert the primary value of a response header as a {@link String}.
*/
public ResultMatcher string(final String name, final String value) {
return string(name, Matchers.equalTo(value));
return new ResultMatcher() {
public void match(MvcResult result) {
assertEquals("Response header", value, result.getResponse().getHeader(name));
}
};
}
/**

View File

@ -17,11 +17,10 @@
package org.springframework.test.web.servlet.result;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import static org.springframework.test.util.AssertionErrors.assertTrue;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.ui.ModelMap;
@ -62,8 +61,13 @@ public class ModelResultMatchers {
/**
* Assert a model attribute value.
*/
public ResultMatcher attribute(String name, Object value) {
return attribute(name, Matchers.equalTo(value));
public ResultMatcher attribute(final String name, final Object value) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
assertEquals("Model attribute '" + name + "'", value, mav.getModel().get(name));
}
};
}
/**
@ -72,9 +76,9 @@ public class ModelResultMatchers {
public ResultMatcher attributeExists(final String... names) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
assertTrue("No ModelAndView found", result.getModelAndView() != null);
ModelAndView mav = getModelAndView(result);
for (String name : names) {
attribute(name, Matchers.notNullValue()).match(result);
assertTrue("Model attribute '" + name + "' does not exist", mav.getModel().get(name) != null);
}
}
};

View File

@ -17,6 +17,7 @@
package org.springframework.test.web.servlet.result;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import java.util.concurrent.Callable;
@ -24,7 +25,6 @@ import java.util.concurrent.Callable;
import javax.servlet.http.HttpServletRequest;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
@ -112,7 +112,7 @@ public class RequestResultMatchers {
@SuppressWarnings("unchecked")
public void match(MvcResult result) {
T value = (T) result.getRequest().getAttribute(name);
assertThat("Request attribute: ", value, matcher);
assertThat("Request attribute", value, matcher);
}
};
}
@ -120,8 +120,12 @@ public class RequestResultMatchers {
/**
* Assert a request attribute value.
*/
public <T> ResultMatcher attribute(String name, Object value) {
return attribute(name, Matchers.equalTo(value));
public <T> ResultMatcher attribute(final String name, final Object expectedValue) {
return new ResultMatcher() {
public void match(MvcResult result) {
assertEquals("Request attribute", expectedValue, result.getRequest().getAttribute(name));
}
};
}
/**
@ -132,7 +136,7 @@ public class RequestResultMatchers {
@SuppressWarnings("unchecked")
public void match(MvcResult result) {
T value = (T) result.getRequest().getSession().getAttribute(name);
assertThat("Request attribute: ", value, matcher);
assertThat("Request attribute", value, matcher);
}
};
}
@ -140,8 +144,12 @@ public class RequestResultMatchers {
/**
* Assert a session attribute value..
*/
public <T> ResultMatcher sessionAttribute(String name, Object value) {
return sessionAttribute(name, Matchers.equalTo(value));
public <T> ResultMatcher sessionAttribute(final String name, final Object value) {
return new ResultMatcher() {
public void match(MvcResult result) {
assertEquals("Request attribute", value, result.getRequest().getSession().getAttribute(name));
}
};
}
}

View File

@ -19,7 +19,6 @@ import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
@ -48,7 +47,7 @@ public class StatusResultMatchers {
public ResultMatcher is(final Matcher<Integer> matcher) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
assertThat("Status: ", result.getResponse().getStatus(), matcher);
assertThat("Response status", result.getResponse().getStatus(), matcher);
}
};
}
@ -56,8 +55,12 @@ public class StatusResultMatchers {
/**
* Assert the response status code is equal to an integer value.
*/
public ResultMatcher is(int status) {
return is(Matchers.equalTo(status));
public ResultMatcher is(final int status) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
assertEquals("Response status", status, result.getResponse().getStatus());
}
};
}
@ -67,7 +70,7 @@ public class StatusResultMatchers {
public ResultMatcher reason(final Matcher<? super String> matcher) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
assertThat("Status reason: ", result.getResponse().getErrorMessage(), matcher);
assertThat("Response status reason", result.getResponse().getErrorMessage(), matcher);
}
};
}
@ -75,8 +78,12 @@ public class StatusResultMatchers {
/**
* Assert the Servlet response error message.
*/
public ResultMatcher reason(String reason) {
return reason(Matchers.equalTo(reason));
public ResultMatcher reason(final String reason) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
assertEquals("Response status reason", reason, result.getResponse().getErrorMessage());
}
};
}
/**

View File

@ -17,10 +17,9 @@
package org.springframework.test.web.servlet.result;
import static org.springframework.test.util.MatcherAssertionErrors.assertThat;
import static org.springframework.test.util.AssertionErrors.assertTrue;
import static org.springframework.test.util.AssertionErrors.*;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.web.servlet.ModelAndView;
@ -56,8 +55,13 @@ public class ViewResultMatchers {
/**
* Assert the selected view name.
*/
public ResultMatcher name(final String name) {
return name(Matchers.equalTo(name));
public ResultMatcher name(final String expectedViewName) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
ModelAndView mav = result.getModelAndView();
assertTrue("No ModelAndView found", mav != null);
assertEquals("View name", expectedViewName, mav.getViewName());
}
};
}
}

View File

@ -21,7 +21,6 @@ import java.util.Map;
import javax.xml.xpath.XPathExpressionException;
import org.hamcrest.Matcher;
import org.hamcrest.Matchers;
import org.springframework.test.util.XpathExpectationsHelper;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
@ -75,14 +74,24 @@ public class XpathResultMatchers {
* Evaluate the XPath and assert that content exists.
*/
public ResultMatcher exists() {
return node(Matchers.notNullValue());
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xpathHelper.exists(content);
}
};
}
/**
* Evaluate the XPath and assert that content doesn't exist.
*/
public ResultMatcher doesNotExist() {
return node(Matchers.nullValue());
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xpathHelper.doesNotExist(content);
}
};
}
/**
@ -101,8 +110,13 @@ public class XpathResultMatchers {
/**
* Evaluate the XPath and assert the number of nodes found.
*/
public ResultMatcher nodeCount(int count) {
return nodeCount(Matchers.equalTo(count));
public ResultMatcher nodeCount(final int expectedCount) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xpathHelper.assertNodeCount(content, expectedCount);
}
};
}
/**
@ -121,8 +135,13 @@ public class XpathResultMatchers {
/**
* Apply the XPath and assert the {@link String} value found.
*/
public ResultMatcher string(String value) {
return string(Matchers.equalTo(value));
public ResultMatcher string(final String expectedValue) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xpathHelper.assertString(content, expectedValue);
}
};
}
/**
@ -141,8 +160,13 @@ public class XpathResultMatchers {
/**
* Evaluate the XPath and assert the {@link Double} value found.
*/
public ResultMatcher number(Double value) {
return number(Matchers.equalTo(value));
public ResultMatcher number(final Double expectedValue) {
return new ResultMatcher() {
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xpathHelper.assertNumber(content, expectedValue);
}
};
}
/**

View File

@ -15,6 +15,8 @@
*/
package org.springframework.test.util;
import org.springframework.util.ObjectUtils;
/**
* JUnit independent assertion class.
*
@ -24,13 +26,14 @@ package org.springframework.test.util;
*/
public abstract class AssertionErrors {
private AssertionErrors() {
}
/**
* Fails a test with the given message.
*
* @param message the message
* @param message describes the reason for the failure
*/
public static void fail(String message) {
throw new AssertionError(message);
@ -40,17 +43,26 @@ public abstract class AssertionErrors {
* Fails a test with the given message passing along expected and actual
* values to be added to the message.
*
* @param message the message
* @param expected the expected value
* @param actual the actual value
* <p>For example given:
* <pre>
* assertEquals("Response header [" + name + "]", actual, expected);
* </pre>
* <p>The resulting message is:
* <pre>
* Response header [Accept] expected:&lt;application/json&gt; but was:&lt;text/plain&gt;
* </pre>
*
* @param message describes the value that failed the match
* @param expected expected value
* @param actual actual value
*/
public static void fail(String message, Object expected, Object actual) {
throw new AssertionError(message + " expected:<" + expected + "> but was:<" + actual + ">");
}
/**
* Asserts that a condition is {@code true}. If not, throws an
* {@link AssertionError} with the given message.
* Assert the given condition is {@code true} and raise an
* {@link AssertionError} if it is not.
*
* @param message the message
* @param condition the condition to test for
@ -62,21 +74,20 @@ public abstract class AssertionErrors {
}
/**
* Asserts that two objects are equal. If not, an {@link AssertionError} is
* thrown with the given message.
* Assert two objects are equal raise an {@link AssertionError} if not.
* <p>For example:
* <pre>
* assertEquals("Response header [" + name + "]", actual, expected);
* </pre>
*
* @param message the message
* @param message describes the value being checked
* @param expected the expected value
* @param actual the actual value
*/
public static void assertEquals(String message, Object expected, Object actual) {
if (expected == null && actual == null) {
return;
}
if (expected != null && expected.equals(actual)) {
return;
}
fail(message, expected, actual);
if (!ObjectUtils.nullSafeEquals(expected, actual)) {
fail(message, expected, actual);
}
}
}