我目前正在使用Spring boot测试我的一个服务,test.The服务会导出所有用户数据,并在成功完成后生成一个CSV或PDF。在浏览器中下载了一个文件。
下面是我在测试类中编写的代码
MvcResult result = MockMvc.perform(post("/api/user-accounts/export").param("query","id=='123'")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_PDF_VALUE)
.content(TestUtil.convertObjectToJsonBytes(userObjectDTO)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_PDF_VALUE))
.andReturn();
String content = result.getResponse().getContentAsString(); // verify the response string.下面是我的资源类代码(调用到这个地方)-
@PostMapping("/user-accounts/export")
@Timed
public ResponseEntity<byte[]> exportAllUsers(@RequestParam Optional<String> query, @ApiParam Pageable pageable,
@RequestBody UserObjectDTO userObjectDTO) {
HttpHeaders headers = new HttpHeaders();
.
.
.
return new ResponseEntity<>(outputContents, headers, HttpStatus.OK);
}当我调试我的服务,并将debug放在退出之前时,我得到的内容类型为'application/pdf‘,状态为200。我尝试在我的测试用例中复制相同的内容类型。不知何故,它总是在执行过程中抛出以下错误-
java.lang.AssertionError: Status
Expected :200
Actual :406我想知道,我应该如何检查我的回答(ResponseEntity)。还有什么应该是响应所需的内容类型。
发布于 2019-01-18 02:49:11
我在@veeram的帮助下找到了答案,并逐渐了解到我的MappingJackson2HttpMessageConverter配置没有满足我的要求。我覆盖了它默认支持的Mediatype,它解决了这个问题。
默认支持-
implication/json
application*/json为解决此问题所做的代码更改-
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.ALL);
jacksonMessageConverter.setSupportedMediaTypes(mediaTypes);发布于 2019-01-15 13:32:33
你在其他地方也有问题。根据application/problem+json内容类型的说明,似乎发生了异常/错误。这可能是在异常处理程序中设置的。因为您的客户端只期望返回application/pdf406。
您可以添加一个测试用例来读取错误详细信息,以了解错误的确切内容。
就像这样
MvcResult result = MockMvc.perform(post("/api/user-accounts/export").param("query","id=='123'")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.accept(MediaType.APPLICATION_PROBLEM_JSON_VALUE)
.content(TestUtil.convertObjectToJsonBytes(userObjectDTO)))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE))
.andReturn();
String content = result.getResponse().getContentAsString(); // This should show you what the error is and you can adjust your code accordingly. 接下来,如果您期望出现错误,可以更改接受类型以同时包含pdf和problem json类型。
注意--此行为取决于您拥有的spring web mvc版本。
最新的spring mvc版本考虑了响应实体中设置的内容类型标头,忽略了accept标头中提供的内容,并将响应解析为可能的格式。因此,相同的测试不会返回406代码,而是返回带有应用程序json问题内容类型的内容。
发布于 2019-01-14 12:40:51
意味着你的客户端正在请求一个服务器认为它不能提供的contentType (可能是pdf)。
我猜测您的代码在调试时能够正常工作的原因是,您的rest客户端没有像测试代码那样添加请求pdf的ACCEPT头。
要解决此问题,请添加到@PostMapping注记produces = MediaType.APPLICATION_PDF_VALUE中,请参阅https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PostMapping.html#produces--
https://stackoverflow.com/questions/54128369
复制相似问题