Support Charset for character encoding in MockMvc
To improve the developer experience and avoid the use of String literals, this commit provides overloaded support via Charset for character encoding in MockHttpServletRequestBuilder and ContentResultMatchers. Closes gh-27231
This commit is contained in:
@@ -477,11 +477,14 @@ class MockHttpServletRequestBuilderTests {
|
||||
@Test
|
||||
void characterEncoding() {
|
||||
String encoding = "UTF-8";
|
||||
|
||||
this.builder.characterEncoding(encoding);
|
||||
|
||||
MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
|
||||
|
||||
assertThat(request.getCharacterEncoding()).isEqualTo(encoding);
|
||||
|
||||
this.builder.characterEncoding(StandardCharsets.ISO_8859_1);
|
||||
request = this.builder.buildRequest(this.servletContext);
|
||||
assertThat(request.getCharacterEncoding()).isEqualTo(StandardCharsets.ISO_8859_1.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -44,10 +44,10 @@ class ResponseBodyTests {
|
||||
void json() throws Exception {
|
||||
standaloneSetup(new PersonController()).defaultResponseCharacterEncoding(UTF_8).build()
|
||||
// We use a name containing an umlaut to test UTF-8 encoding for the request and the response.
|
||||
.perform(get("/person/Jürgen").characterEncoding(UTF_8.name()).accept(MediaType.APPLICATION_JSON))
|
||||
.perform(get("/person/Jürgen").characterEncoding(UTF_8).accept(MediaType.APPLICATION_JSON))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(content().contentType("application/json"))
|
||||
.andExpect(content().encoding(UTF_8.name()))
|
||||
.andExpect(content().encoding(UTF_8))
|
||||
.andExpect(content().string(containsString("Jürgen")))
|
||||
.andExpect(jsonPath("$.name").value("Jürgen"))
|
||||
.andExpect(jsonPath("$.age").value(42))
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
package org.springframework.test.web.servlet.samples.standalone.resultmatchers;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -95,9 +97,17 @@ public class ContentAssertionTests {
|
||||
.andExpect(content().encoding("ISO-8859-1"))
|
||||
.andExpect(content().string(containsString("world")));
|
||||
|
||||
this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN))
|
||||
.andExpect(content().encoding(StandardCharsets.ISO_8859_1))
|
||||
.andExpect(content().string(containsString("world")));
|
||||
|
||||
this.mockMvc.perform(get("/handleUtf8"))
|
||||
.andExpect(content().encoding("UTF-8"))
|
||||
.andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8")));
|
||||
|
||||
this.mockMvc.perform(get("/handleUtf8"))
|
||||
.andExpect(content().encoding(StandardCharsets.UTF_8))
|
||||
.andExpect(content().bytes("\u3053\u3093\u306b\u3061\u306f\u4e16\u754c\uff01".getBytes("UTF-8")));
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user