MockMvc: changing default character encoding of MockHttpServletResponse from ISO-8859-1 to UTF-8

Viewed 3491

While writing Spring Itegration Tests I had the problem that MockMvc ignored my

.accept(MediaType.APPLICATION_JSON_UTF8) 

setting, and returned ISO-8859-1 with bad looking umlaut.

What is the best way to set default encoding of MockMvc to UTF-8?

3 Answers

I red that in spring boot the following setting would help.

spring.http.encoding.force=true

In my case, where the setup is a bit special, it did not.

What does work for my setup is adding a filter to the MockMvc setup.

@Before
  public void setUp() {
    mockMvc = MockMvcBuilders
        .webAppContextSetup(webApplicationContext)
        .addFilter((request, response, chain) -> {
          response.setCharacterEncoding("UTF-8"); // this is crucial
          chain.doFilter(request, response);
        }, "/*")
        .build();
  }

Hope it helps someone and saves some hours of try and error.

This worked for me (Spring Framework 5.3.18):

MockMvcBuilders.defaultResponseCharacterEncoding(StandardCharsets.UTF_8)

For example:

MockMvc mockMvc = MockMvcBuilders
                   .standaloneSetup(controller)
                   .defaultResponseCharacterEncoding(StandardCharsets.UTF_8)
                 .build();
Related