I use getContentAsString() and mockMvc seems to return my Content as ISO 8859-1. Before (with Spring Boot 2.1.8) it was proper UTF-8

When I add a produces to my Endpoint like @GetMapping(value = "/test", produces={"application/json; charset=UTF-8"}) it works as indented. But I dont want todo this on our big project with tons of endpoints

Example:

@RestController
@RequestMapping("test")
public class TestClass {
  @GetMapping
  public List<String> test() {
    return List.of("AEß");
  }
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
@AutoConfigureMockMvc()
@ActiveProfiles("test")
@Transactional
public class TestClassTest {
  @Autowired
  private ObjectMapper objectMapper;
  @Autowired
  private MockMvc mvc;
  @Test
  public void test() throws Exception {
    var mvcResult = mvc.perform(MockMvcRequestBuilders
      .get("/test")
      .contentType(MediaType.APPLICATION_JSON)
      .accept(MediaType.APPLICATION_JSON))
      .andExpect(MockMvcResultMatchers.status().isOk())
      .andReturn();

    assertEquals(List.of("AEß"), objectMapper.readValue(mvcResult.getResponse().getContentAsString(),
      new TypeReference<List<String>>() {
      }));
  }
}

Fails with:

java.lang.AssertionError: 
Expected :[AEß]
Actual   :[AEß]

Originally posted by @chrisaige in https://github.com/spring-projects/spring-framework/issues/23622#issuecomment-545322300

Comment From: sbrannen

What happens if you do the following?

assertEquals(List.of("AEß"), 
   objectMapper.readValue(mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8),
   new TypeReference<List<String>>() {}));

Comment From: spring-projects-issues

If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.

Comment From: stijnvanbael

This issue still exists in Spring Boot 2.2.4. Calling mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8) solves the problem for that one response. But how can I configure UTF8 as the default instead of ISO-8859-1?

Comment From: OmarHawk

hi,

maybe this is also caused by the issue #24813 I have created.

Comment From: sbrannen

This issue still exists in Spring Boot 2.2.4. Calling mvcResult.getResponse().getContentAsString(StandardCharsets.UTF_8) solves the problem for that one response. But how can I configure UTF8 as the default instead of ISO-8859-1?

@stijnvanbael, you may be interested in the new setDefaultCharacterEncoding(String characterEncoding) method I introduced in MockHttpServletResponse in e4b9b1fadb35c4e439acc8931910aaba6e1342e3.