Add a dateValue HeaderResultMatcher
HTTP headers such as "Expires", "Last-Modified" all use date
strings like "Tue, 21 Jul 2015 10:00:00 GMT". Prior to this commit,
there was no way to match those header values, besides formatting dates
manually.
This commit introduces a new HeaderResultMatcher to test those date
headers using a long timestamp:
```
this.mockMvc.perform(get("/persons/1").header("If-Modified-Since", now))
.andExpect(status().isNotModified())
.andExpect(header().dateValue("Last-Modified", timestamp));
```
Issue: SPR-13263
This commit is contained in:
@@ -24,6 +24,11 @@ import org.springframework.test.web.servlet.ResultMatcher;
|
||||
import static org.hamcrest.MatcherAssert.*;
|
||||
import static org.springframework.test.util.AssertionErrors.*;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
import java.util.TimeZone;
|
||||
|
||||
/**
|
||||
* Factory for response header assertions.
|
||||
* <p>An instance of this class is usually accessed via
|
||||
@@ -31,6 +36,7 @@ import static org.springframework.test.util.AssertionErrors.*;
|
||||
*
|
||||
* @author Rossen Stoyanchev
|
||||
* @author Sam Brannen
|
||||
* @author Brian Clozel
|
||||
* @since 3.2
|
||||
*/
|
||||
public class HeaderResultMatchers {
|
||||
@@ -96,4 +102,26 @@ public class HeaderResultMatchers {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert the primary value of the named response header as a date String,
|
||||
* using the preferred date format described in RFC 7231.
|
||||
* <p>The {@link ResultMatcher} returned by this method throws an {@link AssertionError}
|
||||
* if the response does not contain the specified header, or if the supplied
|
||||
* {@code value} does not match the primary value.
|
||||
*
|
||||
* @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a>
|
||||
* @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"));
|
||||
assertTrue("Response does not contain header " + name, result.getResponse().containsHeader(name));
|
||||
assertEquals("Response header " + name, format.format(new Date(value)), result.getResponse().getHeader(name));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user