Search code examples
springjunitspring-testmockmvcspring-test-mvc

Spring MockMVC defaults wrong ContentType in Response


I've just updated my application to use spring-test 5.3.12 and Junit 5.7.2 but now my test are failing.

With the previous version (5.2.X) the response type always was 'application/json' but now I'm getting this error:

java.lang.AssertionError: Content type expected:<application/json> but 
was:<application/json;charset=UTF-8>
Expected :application/json
Actual   :application/json;charset=UTF-8

I've checked that the content Type on the response is, in fact, application/json with Postman, Browser and Swagger

Failing test example

@Test
void whenGetReleaseNotesAppVersionWithNoExistingCodeThenNotFoundInJsonFormat() throws Exception {
    this.mvc.perform(get(
            NEWER_RELEASES_PATH_UPDATE_CONFIG + "/"
                    + "6.0.0" + "/notes")
                        .header(AUTH_HEADER, AUTH_TOKEN_SRVCGERETDESAX)
                        .locale(Locale.ENGLISH)
                        .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isNotFound())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath(
                "$.code", is(ApiErrorCode.RELEASE_NOTES_NOT_FOUND.getCode())));
}

Can't change MediaType to APPLICATION_JSON_UTF8 because is now deprecated, so I can't figure out how fix this.

MockMVC is just autowired, without further configuration

   @Autowired
   private MockMvc mvc;

Annotations in class

@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {
        Application.class })
@ActiveProfiles({ "test" })
@EnableAutoConfiguration
@AutoConfigureMockMvc
class UpdateConfigControllerIT {...}

Solution

  • Either declare the fully expected content type by adding the charset:

    .andExpect(content().contentType(new MediaType(MediaType.APPLICATION_JSON, StandardCharsets.UTF_8)))
    

    or use contentTypeCompatibleWith:

    .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
    

    Just a small note; you can safely remove the @ExtendWith(SpringExtension.class) annotation as the @SpringBootTest annotation is already meta-annotated with the given annotation.