【问题标题】:Spring Boot MockMVC Unit Testing | application/xml;charset=ISO-8859-1Spring Boot MockMVC 单元测试 |应用程序/xml;charset=ISO-8859-1
【发布时间】:2019-05-18 01:14:33
【问题描述】:

我正在测试一个端点并且响应内容类型是“application/xml;charset=ISO-8859-1”,而我期望它是“application/xml”。你能看到我在哪里错误配置了生产方面吗?我将它添加到函数的@RequestMapping 并收到了相同的意外结果。

待测功能

@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);
    }

}

测试

@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));
}

【问题讨论】:

  • 这可能是因为您在@Controller 注释之后缺少@ResponseBody 注释,@Controller@RestController 之间存在细微差别(= @Controller + @ResponseBody

标签: unit-testing spring-mvc spring-boot


【解决方案1】:

如果您只使用application/xml 作为您的生产/接受配置(通过您使用的方法完成),它使用默认字符集,出于兼容性原因,该字符集设置为您要返回的 ISO 字符集。我今天和昨天都遇到了同样的问题,解决方案是明确传递application/xml;charset=utf-8 作为 contentType 并接受标头,并检查您是否获得application/xml;charset=utf-8 作为返回内容的 contentType。最简单的方法是使用 new MediaType(MediaType.APPLICATION_XML.getType(), MediaType.APPLICATION_XML.getSubType(), StandardCharSets.UTF_8) 构造函数来构造它,为 application/xml;charset=UTF-8 创建一个新的 MediaType,然后您可以在测试请求中使用它。

【讨论】:

    【解决方案2】:

    默认 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 2015-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 2016-10-12
      • 2015-01-01
      • 2017-07-14
      相关资源
      最近更新 更多