Improve charset handling in MockHttpServletResponse

This commit adds a getContentAsString(Charset fallbackCharset) method
to MockHttpServletResponse in order to make it easier to get the content
in a specific charset like UTF-8 when the response charset has not been
explicitly set (by default ISO-8859-1 is used).

JsonPathResultMatchers leverages this new feature to support UTF-8
content out of the box.

Closes gh-23219
This commit is contained in:
Sebastien Deleuze
2019-07-16 11:42:39 +02:00
parent 60a7092977
commit adadffe0e1
4 changed files with 47 additions and 6 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.nio.charset.Charset;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@@ -204,11 +205,32 @@ public class MockHttpServletResponse implements HttpServletResponse {
return this.content.toByteArray();
}
/**
* Get the content of the response body as a {@code String}, using the configured
* {@linkplain #getCharacterEncoding character encoding}.
* @return the content as a {@code String}
* @throws UnsupportedEncodingException if the character encoding is not supported
* @see #getContentAsString(Charset)
*/
public String getContentAsString() throws UnsupportedEncodingException {
return (this.characterEncoding != null ?
this.content.toString(this.characterEncoding) : this.content.toString());
}
/**
* Get the content of the response body as a {@code String}, using the provided
* {@code fallbackCharset} if no charset has been explicitly defined, else using
* using the configured {@linkplain #getCharacterEncoding character encoding}.
* @return the content as a {@code String}
* @throws UnsupportedEncodingException if the character encoding is not supported
* @see #getContentAsString()
*/
public String getContentAsString(Charset fallbackCharset) throws UnsupportedEncodingException {
return isCharset() ?
this.content.toString(this.characterEncoding) :
this.content.toString(fallbackCharset.name());
}
@Override
public void setContentLength(int contentLength) {
this.contentLength = contentLength;

View File

@@ -17,6 +17,7 @@
package org.springframework.test.web.servlet.result;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import com.jayway.jsonpath.JsonPath;
import org.hamcrest.Matcher;
@@ -235,7 +236,7 @@ public class JsonPathResultMatchers {
}
private String getContent(MvcResult result) throws UnsupportedEncodingException {
String content = result.getResponse().getContentAsString();
String content = result.getResponse().getContentAsString(StandardCharsets.UTF_8);
if (StringUtils.hasLength(this.prefix)) {
try {
String reason = String.format("Expected a JSON payload prefixed with \"%s\" but found: %s",