首页 > 解决方案 > Spring Boot MockMVC Unit Testing | application/xml;charset=ISO-8859-1

问题描述

I'm testing an endpoint and the response content-type is "application/xml;charset=ISO-8859-1", when I expect it to be "application/xml". Can you see where I may have misconfigured the produces aspect? I added it to the @RequestMapping for the function and received the same, unexpected, result.

Feature Under Test

@Controller
@RequestMapping(value = "/sitemaps",
    consumes = MediaType.ALL_VALUE,
    produces = MediaType.APPLICATION_XML_VALUE)
public class SitemapQueryControllerImpl implements SitemapQueryController {

    @RequestMapping(value = "/index.xml", method = RequestMethod.GET)
    public ResponseEntity<String> GetSitemapIndex() {
        return new ResponseEntity<>("<Hello>", HttpStatus.OK);
    }

}

Test

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SitemapQueryControllerImpl.class, secure = false)
@ContextConfiguration(classes = {ApplicationTestContext.class})
public class SitemapQueryController_Spec {

    @Autowired
    private MockMvc mockMvc;


    @Before
    public void setup() { }


    @Test
    public void GetSitemapIndex_Successul() throws Exception {

        String expect = "<Hello>";
        mockMvc.perform(get("/sitemaps/index.xml")
                .contentType(MediaType.APPLICATION_XML_VALUE))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE))
                    .andExpect(content().xml(expect));
}

标签: unit-testingspring-mvcspring-boot

解决方案


默认情况下 charset 是 UTF-8,MappingJackson2HttpMessageConverter是管理 charSet 的人。您可以通过实现 bean 并将 charSet 设置为 null 来覆盖。

@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    jsonConverter.setObjectMapper(objectMapper);
    jsonConverter.setDefaultCharset(null);
    return jsonConverter;
}

推荐阅读