5

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?

R.A
  • 1,813
  • 21
  • 29

3 Answers3

9

I read 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.

R.A
  • 1,813
  • 21
  • 29
  • i'm having the same problem and noticed that the default MockMvc doesn't seem to honor the `spring.http.encoding.force=true`, ie. it's missing the `CharacterEncodingFilter` – elonderin Feb 11 '20 at 15:13
  • 2
    Using the `spring.http.encoding.xxx` only works when using `@SpringBootTest` but not with `@WebMvcTest`. The latter only works when also adding `@Import(HttpEncodingAutoConfiguration.class)` – elonderin Feb 11 '20 at 16:12
  • 2
    None of this worked for me. MockMvc can be super frustrating because of things like this. – PlunkettBoy Feb 13 '20 at 22:19
  • You just saved me from an imminent encoding hell, thank you very much. – Celso Pereira Neto May 03 '23 at 19:56
2

This worked for me:

server.servlet.encoding.charset=UTF-8
server.servlet.encoding.force=true

I got the idea from this SO Question: SpringBoot response charset errors

emiryasm
  • 21
  • 2
1

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();
Mads Hoel
  • 113
  • 5