Add MockHttpServletResponse.getDateHeader

This change adds a new `getDateHeader` method that converts date header
Strings to long values - making tests more readable.

This feature is also documented in the "what's new section" for 4.2.
This commit is contained in:
Brian Clozel
2015-09-03 16:03:46 +02:00
parent e81a430e61
commit d3d81c2864
3 changed files with 30 additions and 0 deletions

View File

@@ -23,6 +23,7 @@ import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
@@ -493,6 +494,17 @@ public class MockHttpServletResponse implements HttpServletResponse {
setHeaderValue(name, formatDate(value));
}
public long getDateHeader(String name) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
dateFormat.setTimeZone(GMT);
try {
return dateFormat.parse(getHeader(name)).getTime();
} catch (ParseException exception) {
throw new IllegalArgumentException(
"Value for header '" + name + "' is not a valid Date: " + getHeader(name));
}
}
@Override
public void addDateHeader(String name, long value) {
addHeaderValue(name, formatDate(value));

View File

@@ -36,6 +36,7 @@ import static org.junit.Assert.*;
* @author Rossen Stoyanchev
* @author Rob Winch
* @author Sam Brannen
* @author Brian Clozel
* @since 19.02.2006
*/
public class MockHttpServletResponseTests {
@@ -253,6 +254,21 @@ public class MockHttpServletResponseTests {
assertEquals("Tue, 21 Jul 2015 10:00:01 GMT", response.getHeaders("Last-Modified").get(1));
}
@Test
public void getDateHeader() {
long time = 1437472800000L;
response.setDateHeader("Last-Modified", time);
assertEquals("Tue, 21 Jul 2015 10:00:00 GMT", response.getHeader("Last-Modified"));
assertEquals(time, response.getDateHeader("Last-Modified"));
}
@Test(expected = IllegalArgumentException.class)
public void getInvalidDateHeader() {
response.setHeader("Last-Modified", "invalid");
assertEquals("invalid", response.getHeader("Last-Modified"));
response.getDateHeader("Last-Modified");
}
/**
* SPR-10414
*/

View File

@@ -618,4 +618,6 @@ public @interface MyTestConfig {
allowing common test database configuration to be reused in different
++ApplicationContext++s within a test suite.
** See <<jdbc-embedded-database-unique-names>> for details.
* `MockHttpServletRequest` and `MockHttpServletResponse` now better supports
date header formatting `getDateHeader` and `setDateHeader` methods.