Browse Source

Correct attributeHasNoErrors message in ModelResultMatchers

Includes consistent name quoting and use of Java 8 lambdas.

Issue: SPR-15487
pull/1408/head
Juergen Hoeller 9 years ago
parent
commit
0479dc96c4
  1. 107
      spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java
  2. 147
      spring-test/src/main/java/org/springframework/test/web/servlet/result/CookieResultMatchers.java
  3. 36
      spring-test/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java
  4. 80
      spring-test/src/main/java/org/springframework/test/web/servlet/result/HandlerResultMatchers.java
  5. 79
      spring-test/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java
  6. 100
      spring-test/src/main/java/org/springframework/test/web/servlet/result/JsonPathResultMatchers.java
  7. 196
      spring-test/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java
  8. 81
      spring-test/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java
  9. 83
      spring-test/src/main/java/org/springframework/test/web/servlet/result/StatusResultMatchers.java
  10. 26
      spring-test/src/main/java/org/springframework/test/web/servlet/result/ViewResultMatchers.java
  11. 97
      spring-test/src/main/java/org/springframework/test/web/servlet/result/XpathResultMatchers.java
  12. 55
      spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java

107
spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java

@ -27,7 +27,6 @@ import org.w3c.dom.Node; @@ -27,7 +27,6 @@ import org.w3c.dom.Node;
import org.springframework.http.MediaType;
import org.springframework.test.util.JsonExpectationsHelper;
import org.springframework.test.util.XmlExpectationsHelper;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import static org.hamcrest.MatcherAssert.*;
@ -35,6 +34,7 @@ import static org.springframework.test.util.AssertionErrors.*; @@ -35,6 +34,7 @@ import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for response content assertions.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#content}.
*
@ -74,13 +74,10 @@ public class ContentResultMatchers { @@ -74,13 +74,10 @@ public class ContentResultMatchers {
* {@link #contentTypeCompatibleWith(MediaType)}.
*/
public ResultMatcher contentType(final MediaType contentType) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String actual = result.getResponse().getContentType();
assertTrue("Content type not set", actual != null);
assertEquals("Content type", contentType, MediaType.parseMediaType(actual));
}
return result -> {
String actual = result.getResponse().getContentType();
assertTrue("Content type not set", actual != null);
assertEquals("Content type", contentType, MediaType.parseMediaType(actual));
};
}
@ -97,15 +94,12 @@ public class ContentResultMatchers { @@ -97,15 +94,12 @@ public class ContentResultMatchers {
* content type as defined by {@link MediaType#isCompatibleWith(MediaType)}.
*/
public ResultMatcher contentTypeCompatibleWith(final MediaType contentType) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String actual = result.getResponse().getContentType();
assertTrue("Content type not set", actual != null);
MediaType actualContentType = MediaType.parseMediaType(actual);
assertTrue("Content type [" + actual + "] is not compatible with [" + contentType + "]",
actualContentType.isCompatibleWith(contentType));
}
return result -> {
String actual = result.getResponse().getContentType();
assertTrue("Content type not set", actual != null);
MediaType actualContentType = MediaType.parseMediaType(actual);
assertTrue("Content type [" + actual + "] is not compatible with [" + contentType + "]",
actualContentType.isCompatibleWith(contentType));
};
}
@ -114,12 +108,9 @@ public class ContentResultMatchers { @@ -114,12 +108,9 @@ public class ContentResultMatchers {
* @see HttpServletResponse#getCharacterEncoding()
*/
public ResultMatcher encoding(final String characterEncoding) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
String actual = result.getResponse().getCharacterEncoding();
assertEquals("Character encoding", characterEncoding, actual);
}
return result -> {
String actual = result.getResponse().getCharacterEncoding();
assertEquals("Character encoding", characterEncoding, actual);
};
}
@ -131,36 +122,21 @@ public class ContentResultMatchers { @@ -131,36 +122,21 @@ public class ContentResultMatchers {
* </pre>
*/
public ResultMatcher string(final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertThat("Response content", result.getResponse().getContentAsString(), matcher);
}
};
return result -> assertThat("Response content", result.getResponse().getContentAsString(), matcher);
}
/**
* Assert the response body content as a String.
*/
public ResultMatcher string(final String expectedContent) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Response content", expectedContent, result.getResponse().getContentAsString());
}
};
return result -> assertEquals("Response content", expectedContent, result.getResponse().getContentAsString());
}
/**
* Assert the response body content as a byte array.
*/
public ResultMatcher bytes(final byte[] expectedContent) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Response content", expectedContent, result.getResponse().getContentAsByteArray());
}
};
return result -> assertEquals("Response content", expectedContent, result.getResponse().getContentAsByteArray());
}
/**
@ -174,12 +150,9 @@ public class ContentResultMatchers { @@ -174,12 +150,9 @@ public class ContentResultMatchers {
* @see MockMvcResultMatchers#xpath(String, Map, Object...)
*/
public ResultMatcher xml(final String xmlContent) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xmlHelper.assertXmlEqual(xmlContent, content);
}
return result -> {
String content = result.getResponse().getContentAsString();
xmlHelper.assertXmlEqual(xmlContent, content);
};
}
@ -188,12 +161,9 @@ public class ContentResultMatchers { @@ -188,12 +161,9 @@ public class ContentResultMatchers {
* {@link Matcher}.
*/
public ResultMatcher node(final Matcher<? super Node> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xmlHelper.assertNode(content, matcher);
}
return result -> {
String content = result.getResponse().getContentAsString();
xmlHelper.assertNode(content, matcher);
};
}
@ -203,12 +173,9 @@ public class ContentResultMatchers { @@ -203,12 +173,9 @@ public class ContentResultMatchers {
* @see <a href="http://code.google.com/p/xml-matchers/">xml-matchers</a>
*/
public ResultMatcher source(final Matcher<? super Source> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
xmlHelper.assertSource(content, matcher);
}
return result -> {
String content = result.getResponse().getContentAsString();
xmlHelper.assertSource(content, matcher);
};
}
@ -217,7 +184,6 @@ public class ContentResultMatchers { @@ -217,7 +184,6 @@ public class ContentResultMatchers {
* are "similar" - i.e. they contain the same attribute-value pairs
* regardless of formatting with a lenient checking (extensible, and non-strict array
* ordering).
*
* @param jsonContent the expected JSON content
* @since 4.1
*/
@ -226,30 +192,23 @@ public class ContentResultMatchers { @@ -226,30 +192,23 @@ public class ContentResultMatchers {
}
/**
* Parse the response content and the given string as JSON and assert the two
* are "similar" - i.e. they contain the same attribute-value pairs
* regardless of formatting.
*
* Parse the response content and the given string as JSON and assert the two are "similar" -
* i.e. they contain the same attribute-value pairs regardless of formatting.
* <p>Can compare in two modes, depending on {@code strict} parameter value:
* <ul>
* <li>{@code true}: strict checking. Not extensible, and strict array ordering.</li>
* <li>{@code false}: lenient checking. Extensible, and non-strict array ordering.</li>
* <li>{@code true}: strict checking. Not extensible, and strict array ordering.</li>
* <li>{@code false}: lenient checking. Extensible, and non-strict array ordering.</li>
* </ul>
*
* <p>Use of this matcher requires the <a
* href="http://jsonassert.skyscreamer.org/">JSONassert<a/> library.
*
* @param jsonContent the expected JSON content
* @param strict enables strict checking
* @since 4.2
*/
public ResultMatcher json(final String jsonContent, final boolean strict) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = result.getResponse().getContentAsString();
jsonHelper.assertJsonEqual(jsonContent, content, strict);
}
return result -> {
String content = result.getResponse().getContentAsString();
jsonHelper.assertJsonEqual(jsonContent, content, strict);
};
}

147
spring-test/src/main/java/org/springframework/test/web/servlet/result/CookieResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -20,7 +20,6 @@ import javax.servlet.http.Cookie; @@ -20,7 +20,6 @@ import javax.servlet.http.Cookie;
import org.hamcrest.Matcher;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import static org.hamcrest.MatcherAssert.*;
@ -28,6 +27,7 @@ import static org.springframework.test.util.AssertionErrors.*; @@ -28,6 +27,7 @@ import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for response cookie assertions.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#cookie}.
*
@ -49,13 +49,10 @@ public class CookieResultMatchers { @@ -49,13 +49,10 @@ public class CookieResultMatchers {
* Assert a cookie value with the given Hamcrest {@link Matcher}.
*/
public ResultMatcher value(final String name, final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("Response cookie not found: " + name, cookie != null);
assertThat("Response cookie", cookie.getValue(), matcher);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("Response cookie '" + name + "' not found", cookie != null);
assertThat("Response cookie '" + name + "'", cookie.getValue(), matcher);
};
}
@ -63,13 +60,10 @@ public class CookieResultMatchers { @@ -63,13 +60,10 @@ public class CookieResultMatchers {
* Assert a cookie value.
*/
public ResultMatcher value(final String name, final String expectedValue) {
return new ResultMatcher() {
@Override
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());
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("Response cookie '" + name + "' not found", cookie != null);
assertEquals("Response cookie", expectedValue, cookie.getValue());
};
}
@ -78,12 +72,9 @@ public class CookieResultMatchers { @@ -78,12 +72,9 @@ public class CookieResultMatchers {
* max age is 0 (i.e. expired).
*/
public ResultMatcher exists(final String name) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("No cookie with name: " + name, cookie != null);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("No cookie with name '" + name + "'", cookie != null);
};
}
@ -92,12 +83,9 @@ public class CookieResultMatchers { @@ -92,12 +83,9 @@ public class CookieResultMatchers {
* irrespective of whether max age is 0, i.e. expired.
*/
public ResultMatcher doesNotExist(final String name) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("Unexpected cookie with name " + name, cookie == null);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("Unexpected cookie with name '" + name + "'", cookie == null);
};
}
@ -105,13 +93,10 @@ public class CookieResultMatchers { @@ -105,13 +93,10 @@ public class CookieResultMatchers {
* Assert a cookie's maxAge with a Hamcrest {@link Matcher}.
*/
public ResultMatcher maxAge(final String name, final Matcher<? super Integer> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("No cookie with name: " + name, cookie != null);
assertThat("Response cookie maxAge", cookie.getMaxAge(), matcher);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("No cookie with name '" + name + "'", cookie != null);
assertThat("Response cookie '" + name + "' maxAge", cookie.getMaxAge(), matcher);
};
}
@ -119,13 +104,10 @@ public class CookieResultMatchers { @@ -119,13 +104,10 @@ public class CookieResultMatchers {
* Assert a cookie's maxAge value.
*/
public ResultMatcher maxAge(final String name, final int maxAge) {
return new ResultMatcher() {
@Override
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());
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertTrue("No cookie with name: " + name, cookie != null);
assertEquals("Response cookie '" + name + "' maxAge", maxAge, cookie.getMaxAge());
};
}
@ -133,22 +115,16 @@ public class CookieResultMatchers { @@ -133,22 +115,16 @@ public class CookieResultMatchers {
* Assert a cookie path with a Hamcrest {@link Matcher}.
*/
public ResultMatcher path(final String name, final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie path", cookie.getPath(), matcher);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie '" + name + "' path", cookie.getPath(), matcher);
};
}
public ResultMatcher path(final String name, final String path) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie path", path, cookie.getPath());
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie '" + name + "' path", path, cookie.getPath());
};
}
@ -156,12 +132,9 @@ public class CookieResultMatchers { @@ -156,12 +132,9 @@ public class CookieResultMatchers {
* Assert a cookie's domain with a Hamcrest {@link Matcher}.
*/
public ResultMatcher domain(final String name, final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie domain", cookie.getDomain(), matcher);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie '" + name + "' domain", cookie.getDomain(), matcher);
};
}
@ -169,12 +142,9 @@ public class CookieResultMatchers { @@ -169,12 +142,9 @@ public class CookieResultMatchers {
* Assert a cookie's domain value.
*/
public ResultMatcher domain(final String name, final String domain) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie domain", domain, cookie.getDomain());
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie '" + name + "' domain", domain, cookie.getDomain());
};
}
@ -182,12 +152,9 @@ public class CookieResultMatchers { @@ -182,12 +152,9 @@ public class CookieResultMatchers {
* Assert a cookie's comment with a Hamcrest {@link Matcher}.
*/
public ResultMatcher comment(final String name, final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie comment", cookie.getComment(), matcher);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie '" + name + "' comment", cookie.getComment(), matcher);
};
}
@ -195,12 +162,9 @@ public class CookieResultMatchers { @@ -195,12 +162,9 @@ public class CookieResultMatchers {
* Assert a cookie's comment value.
*/
public ResultMatcher comment(final String name, final String comment) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie comment", comment, cookie.getComment());
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie '" + name + "' comment", comment, cookie.getComment());
};
}
@ -208,12 +172,9 @@ public class CookieResultMatchers { @@ -208,12 +172,9 @@ public class CookieResultMatchers {
* Assert a cookie's version with a Hamcrest {@link Matcher}
*/
public ResultMatcher version(final String name, final Matcher<? super Integer> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie version", cookie.getVersion(), matcher);
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertThat("Response cookie '" + name + "' version", cookie.getVersion(), matcher);
};
}
@ -221,12 +182,9 @@ public class CookieResultMatchers { @@ -221,12 +182,9 @@ public class CookieResultMatchers {
* Assert a cookie's version value.
*/
public ResultMatcher version(final String name, final int version) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie version", version, cookie.getVersion());
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie '" + name + "' version", version, cookie.getVersion());
};
}
@ -234,12 +192,9 @@ public class CookieResultMatchers { @@ -234,12 +192,9 @@ public class CookieResultMatchers {
* Assert whether the cookie must be sent over a secure protocol or not.
*/
public ResultMatcher secure(final String name, final boolean secure) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie secure", secure, cookie.getSecure());
}
return result -> {
Cookie cookie = result.getResponse().getCookie(name);
assertEquals("Response cookie '" + name + "' secure", secure, cookie.getSecure());
};
}

36
spring-test/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -18,7 +18,6 @@ package org.springframework.test.web.servlet.result; @@ -18,7 +18,6 @@ package org.springframework.test.web.servlet.result;
import org.hamcrest.Matcher;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import static org.hamcrest.MatcherAssert.*;
@ -26,6 +25,7 @@ import static org.springframework.test.util.AssertionErrors.*; @@ -26,6 +25,7 @@ import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for "output" flash attribute assertions.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#flash}.
*
@ -45,38 +45,25 @@ public class FlashAttributeResultMatchers { @@ -45,38 +45,25 @@ public class FlashAttributeResultMatchers {
/**
* Assert a flash attribute's value with the given Hamcrest {@link Matcher}.
*/
@SuppressWarnings("unchecked")
public <T> ResultMatcher attribute(final String name, final Matcher<T> matcher) {
return new ResultMatcher() {
@Override
@SuppressWarnings("unchecked")
public void match(MvcResult result) throws Exception {
assertThat("Flash attribute", (T) result.getFlashMap().get(name), matcher);
}
};
return result -> assertThat("Flash attribute '" + name + "'", (T) result.getFlashMap().get(name), matcher);
}
/**
* Assert a flash attribute's value.
*/
public <T> ResultMatcher attribute(final String name, final Object value) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Flash attribute", value, result.getFlashMap().get(name));
}
};
return result -> assertEquals("Flash attribute '" + name + "'", value, result.getFlashMap().get(name));
}
/**
* Assert the existence of the given flash attributes.
*/
public <T> ResultMatcher attributeExists(final String... names) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
for (String name : names) {
assertTrue("Flash attribute [" + name + "] does not exist", result.getFlashMap().get(name) != null);
}
return result -> {
for (String name : names) {
assertTrue("Flash attribute '" + name + "' does not exist", result.getFlashMap().get(name) != null);
}
};
}
@ -85,12 +72,7 @@ public class FlashAttributeResultMatchers { @@ -85,12 +72,7 @@ public class FlashAttributeResultMatchers {
* Assert the number of flash attributes.
*/
public <T> ResultMatcher attributeCount(final int count) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("FlashMap size", count, result.getFlashMap().size());
}
};
return result -> assertEquals("FlashMap size must be " + count, count, result.getFlashMap().size());
}
}

80
spring-test/src/main/java/org/springframework/test/web/servlet/result/HandlerResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -29,13 +29,12 @@ import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBui @@ -29,13 +29,12 @@ import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBui
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.AssertionErrors.assertTrue;
import static org.springframework.test.util.AssertionErrors.fail;
import static org.hamcrest.MatcherAssert.*;
import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for assertions on the selected handler or handler method.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#handler}.
*
@ -50,7 +49,6 @@ import static org.springframework.test.util.AssertionErrors.fail; @@ -50,7 +49,6 @@ import static org.springframework.test.util.AssertionErrors.fail;
*/
public class HandlerResultMatchers {
/**
* Protected constructor.
* Use {@link MockMvcResultMatchers#handler()}.
@ -63,17 +61,14 @@ public class HandlerResultMatchers { @@ -63,17 +61,14 @@ public class HandlerResultMatchers {
* Assert the type of the handler that processed the request.
*/
public ResultMatcher handlerType(final Class<?> type) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
Object handler = result.getHandler();
assertTrue("No handler: ", handler != null);
Class<?> actual = handler.getClass();
if (HandlerMethod.class.isInstance(handler)) {
actual = ((HandlerMethod) handler).getBeanType();
}
assertEquals("Handler type", type, ClassUtils.getUserClass(actual));
return result -> {
Object handler = result.getHandler();
assertTrue("No handler", handler != null);
Class<?> actual = handler.getClass();
if (HandlerMethod.class.isInstance(handler)) {
actual = ((HandlerMethod) handler).getBeanType();
}
assertEquals("Handler type", type, ClassUtils.getUserClass(actual));
};
}
@ -103,19 +98,16 @@ public class HandlerResultMatchers { @@ -103,19 +98,16 @@ public class HandlerResultMatchers {
* or the "mock" controller itself after an invocation
*/
public ResultMatcher methodCall(final Object obj) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
if (!MethodInvocationInfo.class.isInstance(obj)) {
fail(String.format("The supplied object [%s] is not an instance of %s. "
+ "Ensure that you invoke the handler method via MvcUriComponentsBuilder.on().",
obj, MethodInvocationInfo.class.getName()));
}
MethodInvocationInfo invocationInfo = (MethodInvocationInfo) obj;
Method expected = invocationInfo.getControllerMethod();
Method actual = getHandlerMethod(result).getMethod();
assertEquals("Handler method", expected, actual);
return result -> {
if (!(obj instanceof MethodInvocationInfo)) {
fail(String.format("The supplied object [%s] is not an instance of %s. " +
"Ensure that you invoke the handler method via MvcUriComponentsBuilder.on().",
obj, MethodInvocationInfo.class.getName()));
}
MethodInvocationInfo invocationInfo = (MethodInvocationInfo) obj;
Method expected = invocationInfo.getControllerMethod();
Method actual = getHandlerMethod(result).getMethod();
assertEquals("Handler method", expected, actual);
};
}
@ -124,12 +116,9 @@ public class HandlerResultMatchers { @@ -124,12 +116,9 @@ public class HandlerResultMatchers {
* using the given Hamcrest {@link Matcher}.
*/
public ResultMatcher methodName(final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
HandlerMethod handlerMethod = getHandlerMethod(result);
assertThat("Handler method", handlerMethod.getMethod().getName(), matcher);
}
return result -> {
HandlerMethod handlerMethod = getHandlerMethod(result);
assertThat("Handler method", handlerMethod.getMethod().getName(), matcher);
};
}
@ -137,12 +126,9 @@ public class HandlerResultMatchers { @@ -137,12 +126,9 @@ public class HandlerResultMatchers {
* Assert the name of the controller method used to process the request.
*/
public ResultMatcher methodName(final String name) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
HandlerMethod handlerMethod = getHandlerMethod(result);
assertEquals("Handler method", name, handlerMethod.getMethod().getName());
}
return result -> {
HandlerMethod handlerMethod = getHandlerMethod(result);
assertEquals("Handler method", name, handlerMethod.getMethod().getName());
};
}
@ -150,19 +136,17 @@ public class HandlerResultMatchers { @@ -150,19 +136,17 @@ public class HandlerResultMatchers {
* Assert the controller method used to process the request.
*/
public ResultMatcher method(final Method method) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
HandlerMethod handlerMethod = getHandlerMethod(result);
assertEquals("Handler method", method, handlerMethod.getMethod());
}
return result -> {
HandlerMethod handlerMethod = getHandlerMethod(result);
assertEquals("Handler method", method, handlerMethod.getMethod());
};
}
private static HandlerMethod getHandlerMethod(MvcResult result) {
Object handler = result.getHandler();
assertTrue("No handler: ", handler != null);
assertTrue("Not a HandlerMethod: " + handler, HandlerMethod.class.isInstance(handler));
assertTrue("No handler", handler != null);
assertTrue("Not a HandlerMethod: " + handler, handler instanceof HandlerMethod);
return (HandlerMethod) handler;
}

79
spring-test/src/main/java/org/springframework/test/web/servlet/result/HeaderResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -26,15 +26,14 @@ import java.util.TimeZone; @@ -26,15 +26,14 @@ import java.util.TimeZone;
import org.hamcrest.Matcher;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.springframework.test.util.AssertionErrors.assertEquals;
import static org.springframework.test.util.AssertionErrors.assertTrue;
import static org.hamcrest.MatcherAssert.*;
import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for response header assertions.
*
* <p>An instance of this class is available via
* {@link MockMvcResultMatchers#header}.
*
@ -45,7 +44,6 @@ import static org.springframework.test.util.AssertionErrors.assertTrue; @@ -45,7 +44,6 @@ import static org.springframework.test.util.AssertionErrors.assertTrue;
*/
public class HeaderResultMatchers {
/**
* Protected constructor.
* See {@link MockMvcResultMatchers#header()}.
@ -59,12 +57,7 @@ public class HeaderResultMatchers { @@ -59,12 +57,7 @@ public class HeaderResultMatchers {
* String {@code Matcher}.
*/
public ResultMatcher string(final String name, final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
assertThat("Response header " + name, result.getResponse().getHeader(name), matcher);
}
};
return result -> assertThat("Response header '" + name + "'", result.getResponse().getHeader(name), matcher);
}
/**
@ -73,12 +66,9 @@ public class HeaderResultMatchers { @@ -73,12 +66,9 @@ public class HeaderResultMatchers {
* @since 4.3
*/
public <T> ResultMatcher stringValues(final String name, final Matcher<Iterable<String>> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
List<String> values = result.getResponse().getHeaders(name);
assertThat("Response header " + name, values, matcher);
}
return result -> {
List<String> values = result.getResponse().getHeaders(name);
assertThat("Response header '" + name + "'", values, matcher);
};
}
@ -86,12 +76,7 @@ public class HeaderResultMatchers { @@ -86,12 +76,7 @@ public class HeaderResultMatchers {
* Assert the primary value of the response header as a String value.
*/
public ResultMatcher string(final String name, final String value) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
assertEquals("Response header " + name, value, result.getResponse().getHeader(name));
}
};
return result -> assertEquals("Response header '" + name + "'", value, result.getResponse().getHeader(name));
}
/**
@ -99,12 +84,9 @@ public class HeaderResultMatchers { @@ -99,12 +84,9 @@ public class HeaderResultMatchers {
* @since 4.3
*/
public ResultMatcher stringValues(final String name, final String... values) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
List<Object> actual = result.getResponse().getHeaderValues(name);
assertEquals("Response header " + name, Arrays.asList(values), actual);
}
return result -> {
List<Object> actual = result.getResponse().getHeaderValues(name);
assertEquals("Response header '" + name + "'", Arrays.asList(values), actual);
};
}
@ -113,13 +95,8 @@ public class HeaderResultMatchers { @@ -113,13 +95,8 @@ public class HeaderResultMatchers {
* @since 4.0
*/
public ResultMatcher doesNotExist(final String name) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
assertTrue("Response should not contain header " + name,
!result.getResponse().containsHeader(name));
}
};
return result -> assertTrue("Response should not contain header '" + name + "'",
!result.getResponse().containsHeader(name));
}
/**
@ -129,13 +106,10 @@ public class HeaderResultMatchers { @@ -129,13 +106,10 @@ public class HeaderResultMatchers {
* header, or if the supplied {@code value} does not match the primary value.
*/
public ResultMatcher longValue(final String name, final long value) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
MockHttpServletResponse response = result.getResponse();
assertTrue("Response does not contain header " + name, response.containsHeader(name));
assertEquals("Response header " + name, value, Long.parseLong(response.getHeader(name)));
}
return result -> {
MockHttpServletResponse response = result.getResponse();
assertTrue("Response does not contain header '" + name + "'", response.containsHeader(name));
assertEquals("Response header '" + name + "'", value, Long.parseLong(response.getHeader(name)));
};
}
@ -149,16 +123,13 @@ public class HeaderResultMatchers { @@ -149,16 +123,13 @@ public class HeaderResultMatchers {
* @since 4.2
*/
public ResultMatcher dateValue(final String name, final long value) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String formatted = format.format(new Date(value));
MockHttpServletResponse response = result.getResponse();
assertTrue("Response does not contain header " + name, response.containsHeader(name));
assertEquals("Response header " + name, formatted, response.getHeader(name));
}
return result -> {
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
String formatted = format.format(new Date(value));
MockHttpServletResponse response = result.getResponse();
assertTrue("Response does not contain header '" + name + "'", response.containsHeader(name));
assertEquals("Response header '" + name + "'", formatted, response.getHeader(name));
};
}

100
spring-test/src/main/java/org/springframework/test/web/servlet/result/JsonPathResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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.
@ -31,6 +31,7 @@ import org.springframework.util.StringUtils; @@ -31,6 +31,7 @@ import org.springframework.util.StringUtils;
/**
* Factory for assertions on the response content using
* <a href="https://github.com/jayway/JsonPath">JsonPath</a> expressions.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#jsonPath(String, Matcher)} or
* {@link MockMvcResultMatchers#jsonPath(String, Object...)}.
@ -79,12 +80,9 @@ public class JsonPathResultMatchers { @@ -79,12 +80,9 @@ public class JsonPathResultMatchers {
* assert the resulting value with the given Hamcrest {@link Matcher}.
*/
public <T> ResultMatcher value(final Matcher<T> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValue(content, matcher);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValue(content, matcher);
};
}
@ -93,12 +91,7 @@ public class JsonPathResultMatchers { @@ -93,12 +91,7 @@ public class JsonPathResultMatchers {
* assert that the result is equal to the supplied value.
*/
public ResultMatcher value(final Object expectedValue) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
jsonPathHelper.assertValue(getContent(result), expectedValue);
}
};
return result -> jsonPathHelper.assertValue(getContent(result), expectedValue);
}
/**
@ -109,12 +102,9 @@ public class JsonPathResultMatchers { @@ -109,12 +102,9 @@ public class JsonPathResultMatchers {
* <em>empty</em>.
*/
public ResultMatcher exists() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.exists(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.exists(content);
};
}
@ -126,12 +116,9 @@ public class JsonPathResultMatchers { @@ -126,12 +116,9 @@ public class JsonPathResultMatchers {
* <em>empty</em>.
*/
public ResultMatcher doesNotExist() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.doesNotExist(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.doesNotExist(content);
};
}
@ -146,12 +133,9 @@ public class JsonPathResultMatchers { @@ -146,12 +133,9 @@ public class JsonPathResultMatchers {
* @see #doesNotExist()
*/
public ResultMatcher isEmpty() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValueIsEmpty(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValueIsEmpty(content);
};
}
@ -166,12 +150,9 @@ public class JsonPathResultMatchers { @@ -166,12 +150,9 @@ public class JsonPathResultMatchers {
* @see #doesNotExist()
*/
public ResultMatcher isNotEmpty() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValueIsNotEmpty(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValueIsNotEmpty(content);
};
}
@ -181,12 +162,9 @@ public class JsonPathResultMatchers { @@ -181,12 +162,9 @@ public class JsonPathResultMatchers {
* @since 4.2.1
*/
public ResultMatcher isString() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValueIsString(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValueIsString(content);
};
}
@ -196,12 +174,9 @@ public class JsonPathResultMatchers { @@ -196,12 +174,9 @@ public class JsonPathResultMatchers {
* @since 4.2.1
*/
public ResultMatcher isBoolean() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValueIsBoolean(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValueIsBoolean(content);
};
}
@ -211,12 +186,9 @@ public class JsonPathResultMatchers { @@ -211,12 +186,9 @@ public class JsonPathResultMatchers {
* @since 4.2.1
*/
public ResultMatcher isNumber() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValueIsNumber(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValueIsNumber(content);
};
}
@ -225,12 +197,9 @@ public class JsonPathResultMatchers { @@ -225,12 +197,9 @@ public class JsonPathResultMatchers {
* assert that the result is an array.
*/
public ResultMatcher isArray() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValueIsArray(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValueIsArray(content);
};
}
@ -240,12 +209,9 @@ public class JsonPathResultMatchers { @@ -240,12 +209,9 @@ public class JsonPathResultMatchers {
* @since 4.2.1
*/
public ResultMatcher isMap() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
String content = getContent(result);
jsonPathHelper.assertValueIsMap(content);
}
return result -> {
String content = getContent(result);
jsonPathHelper.assertValueIsMap(content);
};
}

196
spring-test/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -30,6 +30,7 @@ import static org.springframework.test.util.AssertionErrors.*; @@ -30,6 +30,7 @@ import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for assertions on the model.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#model}.
*
@ -49,14 +50,11 @@ public class ModelResultMatchers { @@ -49,14 +50,11 @@ public class ModelResultMatchers {
/**
* Assert a model attribute value with the given Hamcrest {@link Matcher}.
*/
@SuppressWarnings("unchecked")
public <T> ResultMatcher attribute(final String name, final Matcher<T> matcher) {
return new ResultMatcher() {
@Override
@SuppressWarnings("unchecked")
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
assertThat("Model attribute '" + name + "'", (T) mav.getModel().get(name), matcher);
}
return result -> {
ModelAndView mav = getModelAndView(result);
assertThat("Model attribute '" + name + "'", (T) mav.getModel().get(name), matcher);
};
}
@ -64,12 +62,9 @@ public class ModelResultMatchers { @@ -64,12 +62,9 @@ public class ModelResultMatchers {
* Assert a model attribute value.
*/
public ResultMatcher attribute(final String name, final Object value) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
assertEquals("Model attribute '" + name + "'", value, mav.getModel().get(name));
}
return result -> {
ModelAndView mav = getModelAndView(result);
assertEquals("Model attribute '" + name + "'", value, mav.getModel().get(name));
};
}
@ -77,13 +72,10 @@ public class ModelResultMatchers { @@ -77,13 +72,10 @@ public class ModelResultMatchers {
* Assert the given model attributes exist.
*/
public ResultMatcher attributeExists(final String... names) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
for (String name : names) {
assertTrue("Model attribute '" + name + "' does not exist", mav.getModel().get(name) != null);
}
return result -> {
ModelAndView mav = getModelAndView(result);
for (String name : names) {
assertTrue("Model attribute '" + name + "' does not exist", mav.getModel().get(name) != null);
}
};
}
@ -92,29 +84,23 @@ public class ModelResultMatchers { @@ -92,29 +84,23 @@ public class ModelResultMatchers {
* Assert the given model attributes do not exist
*/
public ResultMatcher attributeDoesNotExist(final String... names) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
for (String name : names) {
assertTrue("Model attribute '" + name + "' exists", mav.getModel().get(name) == null);
}
}
};
return result -> {
ModelAndView mav = getModelAndView(result);
for (String name : names) {
assertTrue("Model attribute '" + name + "' exists", mav.getModel().get(name) == null);
}
};
}
/**
* Assert the given model attribute(s) have errors.
*/
public ResultMatcher attributeErrorCount(final String name, final int expectedCount) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
Errors errors = getBindingResult(mav, name);
assertEquals("Binding/validation error count for attribute [" + name + "], ",
expectedCount, errors.getErrorCount());
}
return result -> {
ModelAndView mav = getModelAndView(result);
Errors errors = getBindingResult(mav, name);
assertEquals("Binding/validation error count for attribute '" + name + "', ",
expectedCount, errors.getErrorCount());
};
}
@ -122,14 +108,11 @@ public class ModelResultMatchers { @@ -122,14 +108,11 @@ public class ModelResultMatchers {
* Assert the given model attribute(s) have errors.
*/
public ResultMatcher attributeHasErrors(final String... names) {
return new ResultMatcher() {
@Override
public void match(MvcResult mvcResult) throws Exception {
ModelAndView mav = getModelAndView(mvcResult);
for (String name : names) {
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute [" + name + "]", result.hasErrors());
}
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
for (String name : names) {
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
}
};
}
@ -138,14 +121,12 @@ public class ModelResultMatchers { @@ -138,14 +121,12 @@ public class ModelResultMatchers {
* Assert the given model attribute(s) do not have errors.
*/
public ResultMatcher attributeHasNoErrors(final String... names) {
return new ResultMatcher() {
@Override
public void match(MvcResult mvcResult) throws Exception {
ModelAndView mav = getModelAndView(mvcResult);
for (String name : names) {
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute [" + name + "]", !result.hasErrors());
}
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
for (String name : names) {
BindingResult result = getBindingResult(mav, name);
assertTrue("Unexpected errors for attribute '" + name + "': " + result.getAllErrors(),
!result.hasErrors());
}
};
}
@ -154,16 +135,13 @@ public class ModelResultMatchers { @@ -154,16 +135,13 @@ public class ModelResultMatchers {
* Assert the given model attribute field(s) have errors.
*/
public ResultMatcher attributeHasFieldErrors(final String name, final String... fieldNames) {
return new ResultMatcher() {
@Override
public void match(MvcResult mvcResult) throws Exception {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());
for (final String fieldName : fieldNames) {
boolean hasFieldErrors = result.hasFieldErrors(fieldName);
assertTrue("No errors for field: [" + fieldName + "] of attribute [" + name + "]", hasFieldErrors);
}
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
for (final String fieldName : fieldNames) {
boolean hasFieldErrors = result.hasFieldErrors(fieldName);
assertTrue("No errors for field '" + fieldName + "' of attribute '" + name + "'", hasFieldErrors);
}
};
}
@ -173,18 +151,14 @@ public class ModelResultMatchers { @@ -173,18 +151,14 @@ public class ModelResultMatchers {
* @since 4.1
*/
public ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName, final String error) {
return new ResultMatcher() {
public void match(MvcResult mvcResult) throws Exception {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());
boolean hasFieldErrors = result.hasFieldErrors(fieldName);
assertTrue("No errors for field: [" + fieldName + "] of attribute [" + name + "]", hasFieldErrors);
String code = result.getFieldError(fieldName).getCode();
assertTrue("Expected error code '" + error + "' but got '" + code + "'", code.equals(error));
}
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute '" + name + "'", result.hasErrors());
boolean hasFieldErrors = result.hasFieldErrors(fieldName);
assertTrue("No errors for field '" + fieldName + "' of attribute '" + name + "'", hasFieldErrors);
String code = result.getFieldError(fieldName).getCode();
assertTrue("Expected error code '" + error + "' but got '" + code + "'", code.equals(error));
};
}
@ -195,19 +169,14 @@ public class ModelResultMatchers { @@ -195,19 +169,14 @@ public class ModelResultMatchers {
public <T> ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName,
final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult mvcResult) throws Exception {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());
boolean hasFieldErrors = result.hasFieldErrors(fieldName);
assertTrue("No errors for field: [" + fieldName + "] of attribute [" + name + "]", hasFieldErrors);
String code = result.getFieldError(fieldName).getCode();
assertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher);
}
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
assertTrue("No errors for attribute: [" + name + "]", result.hasErrors());
boolean hasFieldErrors = result.hasFieldErrors(fieldName);
assertTrue("No errors for field '" + fieldName + "' of attribute '" + name + "'", hasFieldErrors);
String code = result.getFieldError(fieldName).getCode();
assertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher);
};
}
@ -215,12 +184,9 @@ public class ModelResultMatchers { @@ -215,12 +184,9 @@ public class ModelResultMatchers {
* Assert the total number of errors in the model.
*/
public <T> ResultMatcher errorCount(final int expectedCount) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
int actualCount = getErrorCount(getModelAndView(result).getModelMap());
assertEquals("Binding/validation error count", expectedCount, actualCount);
}
return result -> {
int actualCount = getErrorCount(getModelAndView(result).getModelMap());
assertEquals("Binding/validation error count", expectedCount, actualCount);
};
}
@ -228,12 +194,9 @@ public class ModelResultMatchers { @@ -228,12 +194,9 @@ public class ModelResultMatchers {
* Assert the model has errors.
*/
public <T> ResultMatcher hasErrors() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
int count = getErrorCount(getModelAndView(result).getModelMap());
assertTrue("Expected binding/validation errors", count != 0);
}
return result -> {
int count = getErrorCount(getModelAndView(result).getModelMap());
assertTrue("Expected binding/validation errors", count != 0);
};
}
@ -241,15 +204,11 @@ public class ModelResultMatchers { @@ -241,15 +204,11 @@ public class ModelResultMatchers {
* Assert the model has no errors.
*/
public <T> ResultMatcher hasNoErrors() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
for (Object value : mav.getModel().values()) {
if (value instanceof Errors) {
assertTrue("Unexpected binding/validation error(s) [" + value + "]",
!((Errors) value).hasErrors());
}
return result -> {
ModelAndView mav = getModelAndView(result);
for (Object value : mav.getModel().values()) {
if (value instanceof Errors) {
assertTrue("Unexpected binding/validation errors: " + value, !((Errors) value).hasErrors());
}
}
};
@ -259,18 +218,15 @@ public class ModelResultMatchers { @@ -259,18 +218,15 @@ public class ModelResultMatchers {
* Assert the number of model attributes.
*/
public <T> ResultMatcher size(final int size) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = getModelAndView(result);
int actual = 0;
for (String key : mav.getModel().keySet()) {
if (!key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
actual++;
}
return result -> {
ModelAndView mav = getModelAndView(result);
int actual = 0;
for (String key : mav.getModel().keySet()) {
if (!key.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
actual++;
}
assertEquals("Model size", size, actual);
}
assertEquals("Model size", size, actual);
};
}

81
spring-test/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -22,7 +22,6 @@ import javax.servlet.http.HttpServletRequest; @@ -22,7 +22,6 @@ import javax.servlet.http.HttpServletRequest;
import org.hamcrest.Matcher;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncTask;
@ -32,6 +31,7 @@ import static org.springframework.test.util.AssertionErrors.*; @@ -32,6 +31,7 @@ import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for assertions on the request.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#request}.
*
@ -59,12 +59,9 @@ public class RequestResultMatchers { @@ -59,12 +59,9 @@ public class RequestResultMatchers {
* perform asynchronous dispatches.
*/
public ResultMatcher asyncStarted() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
HttpServletRequest request = result.getRequest();
assertAsyncStarted(request);
}
return result -> {
HttpServletRequest request = result.getRequest();
assertAsyncStarted(request);
};
}
@ -73,12 +70,9 @@ public class RequestResultMatchers { @@ -73,12 +70,9 @@ public class RequestResultMatchers {
* @see #asyncStarted()
*/
public ResultMatcher asyncNotStarted() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
HttpServletRequest request = result.getRequest();
assertEquals("Async started", false, request.isAsyncStarted());
}
return result -> {
HttpServletRequest request = result.getRequest();
assertEquals("Async started", false, request.isAsyncStarted());
};
}
@ -87,15 +81,12 @@ public class RequestResultMatchers { @@ -87,15 +81,12 @@ public class RequestResultMatchers {
* <p>This method can be used when a controller method returns {@link Callable}
* or {@link WebAsyncTask}.
*/
@SuppressWarnings("unchecked")
public <T> ResultMatcher asyncResult(final Matcher<T> matcher) {
return new ResultMatcher() {
@Override
@SuppressWarnings("unchecked")
public void match(MvcResult result) {
HttpServletRequest request = result.getRequest();
assertAsyncStarted(request);
assertThat("Async result", (T) result.getAsyncResult(), matcher);
}
return result -> {
HttpServletRequest request = result.getRequest();
assertAsyncStarted(request);
assertThat("Async result", (T) result.getAsyncResult(), matcher);
};
}
@ -106,27 +97,21 @@ public class RequestResultMatchers { @@ -106,27 +97,21 @@ public class RequestResultMatchers {
* {@code Callable} or the exception raised.
*/
public <T> ResultMatcher asyncResult(final Object expectedResult) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
HttpServletRequest request = result.getRequest();
assertAsyncStarted(request);
assertEquals("Async result", expectedResult, result.getAsyncResult());
}
return result -> {
HttpServletRequest request = result.getRequest();
assertAsyncStarted(request);
assertEquals("Async result", expectedResult, result.getAsyncResult());
};
}
/**
* Assert a request attribute value with the given Hamcrest {@link Matcher}.
*/
@SuppressWarnings("unchecked")
public <T> ResultMatcher attribute(final String name, final Matcher<T> matcher) {
return new ResultMatcher() {
@Override
@SuppressWarnings("unchecked")
public void match(MvcResult result) {
T value = (T) result.getRequest().getAttribute(name);
assertThat("Request attribute '" + name + "'", value, matcher);
}
return result -> {
T value = (T) result.getRequest().getAttribute(name);
assertThat("Request attribute '" + name + "'", value, matcher);
};
}
@ -134,38 +119,28 @@ public class RequestResultMatchers { @@ -134,38 +119,28 @@ public class RequestResultMatchers {
* Assert a request attribute value.
*/
public <T> ResultMatcher attribute(final String name, final Object expectedValue) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
return result ->
assertEquals("Request attribute '" + name + "'", expectedValue, result.getRequest().getAttribute(name));
}
};
}
/**
* Assert a session attribute value with the given Hamcrest {@link Matcher}.
*/
@SuppressWarnings("unchecked")
public <T> ResultMatcher sessionAttribute(final String name, final Matcher<T> matcher) {
return new ResultMatcher() {
@Override
@SuppressWarnings("unchecked")
public void match(MvcResult result) {
T value = (T) result.getRequest().getSession().getAttribute(name);
assertThat("Session attribute '" + name + "'", value, matcher);
}
return result -> {
T value = (T) result.getRequest().getSession().getAttribute(name);
assertThat("Session attribute '" + name + "'", value, matcher);
};
}
/**
* Assert a session attribute value.
*/
@SuppressWarnings("unchecked")
public <T> ResultMatcher sessionAttribute(final String name, final Object value) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
return result ->
assertEquals("Session attribute '" + name + "'", value, result.getRequest().getSession().getAttribute(name));
}
};
}
private static void assertAsyncStarted(HttpServletRequest request) {

83
spring-test/src/main/java/org/springframework/test/web/servlet/result/StatusResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -27,6 +27,7 @@ import static org.springframework.test.util.AssertionErrors.*; @@ -27,6 +27,7 @@ import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for assertions on the response status.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#status}.
*
@ -50,89 +51,54 @@ public class StatusResultMatchers { @@ -50,89 +51,54 @@ public class StatusResultMatchers {
* Assert the response status code with the given Hamcrest {@link Matcher}.
*/
public ResultMatcher is(final Matcher<Integer> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertThat("Response status", result.getResponse().getStatus(), matcher);
}
};
return result -> assertThat("Response status", result.getResponse().getStatus(), matcher);
}
/**
* Assert the response status code is equal to an integer value.
*/
public ResultMatcher is(final int status) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Response status", status, result.getResponse().getStatus());
}
};
return result -> assertEquals("Response status", status, result.getResponse().getStatus());
}
/**
* Assert the response status code is in the 1xx range.
*/
public ResultMatcher is1xxInformational() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.INFORMATIONAL, getHttpStatusSeries(result));
}
};
return result -> assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.INFORMATIONAL, getHttpStatusSeries(result));
}
/**
* Assert the response status code is in the 2xx range.
*/
public ResultMatcher is2xxSuccessful() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.SUCCESSFUL, getHttpStatusSeries(result));
}
};
return result -> assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.SUCCESSFUL, getHttpStatusSeries(result));
}
/**
* Assert the response status code is in the 3xx range.
*/
public ResultMatcher is3xxRedirection() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.REDIRECTION, getHttpStatusSeries(result));
}
};
return result -> assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.REDIRECTION, getHttpStatusSeries(result));
}
/**
* Assert the response status code is in the 4xx range.
*/
public ResultMatcher is4xxClientError() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.CLIENT_ERROR, getHttpStatusSeries(result));
}
};
return result -> assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.CLIENT_ERROR, getHttpStatusSeries(result));
}
/**
* Assert the response status code is in the 5xx range.
*/
public ResultMatcher is5xxServerError() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.SERVER_ERROR, getHttpStatusSeries(result));
}
};
return result -> assertEquals("Range for response status value " + result.getResponse().getStatus(),
HttpStatus.Series.SERVER_ERROR, getHttpStatusSeries(result));
}
private HttpStatus.Series getHttpStatusSeries(MvcResult result) {
@ -145,24 +111,14 @@ public class StatusResultMatchers { @@ -145,24 +111,14 @@ public class StatusResultMatchers {
* Assert the Servlet response error message with the given Hamcrest {@link Matcher}.
*/
public ResultMatcher reason(final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertThat("Response status reason", result.getResponse().getErrorMessage(), matcher);
}
};
return result -> assertThat("Response status reason", result.getResponse().getErrorMessage(), matcher);
}
/**
* Assert the Servlet response error message.
*/
public ResultMatcher reason(final String reason) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
assertEquals("Response status reason", reason, result.getResponse().getErrorMessage());
}
};
return result -> assertEquals("Response status reason", reason, result.getResponse().getErrorMessage());
}
/**
@ -658,12 +614,7 @@ public class StatusResultMatchers { @@ -658,12 +614,7 @@ public class StatusResultMatchers {
* Match the expected response status to that of the HttpServletResponse
*/
private ResultMatcher matcher(final HttpStatus status) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) {
assertEquals("Status", status.value(), result.getResponse().getStatus());
}
};
return result -> assertEquals("Status", status.value(), result.getResponse().getStatus());
}
}

26
spring-test/src/main/java/org/springframework/test/web/servlet/result/ViewResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -18,7 +18,6 @@ package org.springframework.test.web.servlet.result; @@ -18,7 +18,6 @@ package org.springframework.test.web.servlet.result;
import org.hamcrest.Matcher;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.web.servlet.ModelAndView;
@ -27,6 +26,7 @@ import static org.springframework.test.util.AssertionErrors.*; @@ -27,6 +26,7 @@ import static org.springframework.test.util.AssertionErrors.*;
/**
* Factory for assertions on the selected view.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#view}.
*
@ -47,13 +47,10 @@ public class ViewResultMatchers { @@ -47,13 +47,10 @@ public class ViewResultMatchers {
* Assert the selected view name with the given Hamcrest {@link Matcher}.
*/
public ResultMatcher name(final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = result.getModelAndView();
assertTrue("No ModelAndView found", mav != null);
assertThat("View name", mav.getViewName(), matcher);
}
return result -> {
ModelAndView mav = result.getModelAndView();
assertTrue("No ModelAndView found", mav != null);
assertThat("View name", mav.getViewName(), matcher);
};
}
@ -61,13 +58,10 @@ public class ViewResultMatchers { @@ -61,13 +58,10 @@ public class ViewResultMatchers {
* Assert the selected view name.
*/
public ResultMatcher name(final String expectedViewName) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
ModelAndView mav = result.getModelAndView();
assertTrue("No ModelAndView found", mav != null);
assertEquals("View name", expectedViewName, mav.getViewName());
}
return result -> {
ModelAndView mav = result.getModelAndView();
assertTrue("No ModelAndView found", mav != null);
assertEquals("View name", expectedViewName, mav.getViewName());
};
}

97
spring-test/src/main/java/org/springframework/test/web/servlet/result/XpathResultMatchers.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2017 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.
@ -24,11 +24,11 @@ import org.w3c.dom.Node; @@ -24,11 +24,11 @@ import org.w3c.dom.Node;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.util.XpathExpectationsHelper;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultMatcher;
/**
* Factory for assertions on the response content using XPath expressions.
*
* <p>An instance of this class is typically accessed via
* {@link MockMvcResultMatchers#xpath}.
*
@ -55,17 +55,15 @@ public class XpathResultMatchers { @@ -55,17 +55,15 @@ public class XpathResultMatchers {
this.xpathHelper = new XpathExpectationsHelper(expression, namespaces, args);
}
/**
* Evaluate the XPath and assert the {@link Node} content found with the
* given Hamcrest {@link Matcher}.
*/
public ResultMatcher node(final Matcher<? super Node> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNode(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNode(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
};
}
@ -80,12 +78,9 @@ public class XpathResultMatchers { @@ -80,12 +78,9 @@ public class XpathResultMatchers {
* Evaluate the XPath and assert that content exists.
*/
public ResultMatcher exists() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.exists(response.getContentAsByteArray(), getDefinedEncoding(response));
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.exists(response.getContentAsByteArray(), getDefinedEncoding(response));
};
}
@ -93,12 +88,9 @@ public class XpathResultMatchers { @@ -93,12 +88,9 @@ public class XpathResultMatchers {
* Evaluate the XPath and assert that content doesn't exist.
*/
public ResultMatcher doesNotExist() {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.doesNotExist(response.getContentAsByteArray(), getDefinedEncoding(response));
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.doesNotExist(response.getContentAsByteArray(), getDefinedEncoding(response));
};
}
@ -107,12 +99,9 @@ public class XpathResultMatchers { @@ -107,12 +99,9 @@ public class XpathResultMatchers {
* Hamcrest {@link Matcher}.
*/
public ResultMatcher nodeCount(final Matcher<Integer> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
};
}
@ -120,12 +109,9 @@ public class XpathResultMatchers { @@ -120,12 +109,9 @@ public class XpathResultMatchers {
* Evaluate the XPath and assert the number of nodes found.
*/
public ResultMatcher nodeCount(final int expectedCount) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), expectedCount);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNodeCount(response.getContentAsByteArray(), getDefinedEncoding(response), expectedCount);
};
}
@ -134,12 +120,9 @@ public class XpathResultMatchers { @@ -134,12 +120,9 @@ public class XpathResultMatchers {
* Hamcrest {@link Matcher}.
*/
public ResultMatcher string(final Matcher<? super String> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertString(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertString(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
};
}
@ -147,12 +130,9 @@ public class XpathResultMatchers { @@ -147,12 +130,9 @@ public class XpathResultMatchers {
* Apply the XPath and assert the {@link String} value found.
*/
public ResultMatcher string(final String expectedValue) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertString(response.getContentAsByteArray(), getDefinedEncoding(response), expectedValue);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertString(response.getContentAsByteArray(), getDefinedEncoding(response), expectedValue);
};
}
@ -161,12 +141,9 @@ public class XpathResultMatchers { @@ -161,12 +141,9 @@ public class XpathResultMatchers {
* given Hamcrest {@link Matcher}.
*/
public ResultMatcher number(final Matcher<? super Double> matcher) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNumber(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNumber(response.getContentAsByteArray(), getDefinedEncoding(response), matcher);
};
}
@ -174,12 +151,9 @@ public class XpathResultMatchers { @@ -174,12 +151,9 @@ public class XpathResultMatchers {
* Evaluate the XPath and assert the {@link Double} value found.
*/
public ResultMatcher number(final Double expectedValue) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNumber(response.getContentAsByteArray(), getDefinedEncoding(response), expectedValue);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertNumber(response.getContentAsByteArray(), getDefinedEncoding(response), expectedValue);
};
}
@ -187,13 +161,10 @@ public class XpathResultMatchers { @@ -187,13 +161,10 @@ public class XpathResultMatchers {
* Evaluate the XPath and assert the {@link Boolean} value found.
*/
public ResultMatcher booleanValue(final Boolean value) {
return new ResultMatcher() {
@Override
public void match(MvcResult result) throws Exception {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertBoolean(response.getContentAsByteArray(), getDefinedEncoding(response), value);
}
return result -> {
MockHttpServletResponse response = result.getResponse();
xpathHelper.assertBoolean(response.getContentAsByteArray(), getDefinedEncoding(response), value);
};
}
}
}

55
spring-test/src/test/java/org/springframework/test/web/servlet/samples/standalone/resultmatchers/HeaderAssertionTests.java

@ -1,5 +1,5 @@ @@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2017 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,22 +33,12 @@ import org.springframework.web.bind.annotation.PathVariable; @@ -33,22 +33,12 @@ import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.springframework.http.HttpHeaders.IF_MODIFIED_SINCE;
import static org.springframework.http.HttpHeaders.LAST_MODIFIED;
import static org.springframework.http.HttpHeaders.VARY;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.springframework.http.HttpHeaders.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
/**
* Examples of expectations on response header values.
@ -146,24 +136,20 @@ public class HeaderAssertionTests { @@ -146,24 +136,20 @@ public class HeaderAssertionTests {
fail(ERROR_MESSAGE);
}
catch (AssertionError e) {
if (ERROR_MESSAGE.equals(e.getMessage())) {
throw e;
catch (AssertionError err) {
if (ERROR_MESSAGE.equals(err.getMessage())) {
throw err;
}
assertEquals("Response does not contain header " + "X-Custom-Header", e.getMessage());
assertEquals("Response does not contain header 'X-Custom-Header'", err.getMessage());
}
}
// SPR-10771
@Test
@Test // SPR-10771
public void doesNotExist() throws Exception {
this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist("X-Custom-Header"));
}
// SPR-10771
@Test(expected = AssertionError.class)
@Test(expected = AssertionError.class) // SPR-10771
public void doesNotExistFail() throws Exception {
this.mockMvc.perform(get("/persons/1")).andExpect(header().doesNotExist(LAST_MODIFIED));
}
@ -189,6 +175,7 @@ public class HeaderAssertionTests { @@ -189,6 +175,7 @@ public class HeaderAssertionTests {
this.mockMvc.perform(get("/persons/1")).andExpect(header().longValue("X-Rate-Limiting", 1));
}
private void assertIncorrectResponseHeader(ResultMatcher matcher, String unexpected) throws Exception {
try {
this.mockMvc.perform(get("/persons/1")
@ -197,15 +184,15 @@ public class HeaderAssertionTests { @@ -197,15 +184,15 @@ public class HeaderAssertionTests {
fail(ERROR_MESSAGE);
}
catch (AssertionError e) {
if (ERROR_MESSAGE.equals(e.getMessage())) {
throw e;
catch (AssertionError err) {
if (ERROR_MESSAGE.equals(err.getMessage())) {
throw err;
}
// SPR-10659: ensure header name is in the message
// Unfortunately, we can't control formatting from JUnit or Hamcrest.
assertMessageContains(e, "Response header " + LAST_MODIFIED);
assertMessageContains(e, unexpected);
assertMessageContains(e, now);
assertMessageContains(err, "Response header '" + LAST_MODIFIED + "'");
assertMessageContains(err, unexpected);
assertMessageContains(err, now);
}
}
@ -220,7 +207,6 @@ public class HeaderAssertionTests { @@ -220,7 +207,6 @@ public class HeaderAssertionTests {
private long timestamp;
public void setStubTimestamp(long timestamp) {
this.timestamp = timestamp;
}
@ -239,4 +225,5 @@ public class HeaderAssertionTests { @@ -239,4 +225,5 @@ public class HeaderAssertionTests {
return this.timestamp;
}
}
}

Loading…
Cancel
Save