unit-testing - 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));
}
解决方案
默认情况下 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;
}
推荐阅读
- node.js - 创建一个 API 来包装一个... API?
- angular - 在 Angular 5 中保存和读取图像的最佳实践是什么?
- python-3.x - Pyplot:在图形和颜色条之间添加间距
- python - 你如何真正退出 python 脚本?
- javascript - 如果页面已经轻微滚动,为什么这不起作用?
- python - 如何在Django中获取表数据代替表object_new Object
- entity-framework - 实体框架中的关系数据库急切加载问题
- ios - 如何使用 IBInspectable 数据进行自定义 segue
- python - 基于另一个(不规则)时间序列的下采样时间序列,熊猫
- c - 线程双释放中的卷曲请求