如何为返回PDF文件的Spring Boot测试用例设置内容类型 [英] How to set content-type for a spring boot test case which returns PDF file
问题描述
我目前正在使用Spring boot test测试我的一项服务,该服务导出所有用户数据并在成功完成后生成CSV或PDF.在浏览器中下载文件.
I am currently testing one of my services with Spring boot test.The service exports all user data and produces a CSV or PDF after successful completion. A file is downloade in browser.
下面是我在测试类中编写的代码
Below is the code i have wrote in my test class
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.
下面是我的资源类代码(调用到此位置)-
Below is my resource class code (call comes to this place)-
@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);
}
虽然我调试服务,然后在出口之前进行调试,但是我得到的内容类型为"application/pdf",状态为200.我试图在测试用例中复制相同的内容类型.在执行过程中总以某种方式使其低于错误-
While I debug my service, and place debug just before the exit, I get content Type as 'application/pdf' and status as 200.I have tried to replicate the same content type in my test case. Somehow it always throws below error during execution -
java.lang.AssertionError: Status
Expected :200
Actual :406
我想知道,我应该如何检查我的响应(ResponseEntity).同样,响应所需的内容类型应该是什么.
I would like to know, how should i inspect my response (ResponseEntity). Also what should be the desired content-type for response.
推荐答案
我在@veeram的帮助下找到了答案,并开始理解我的MappingJackson2HttpMessageConverter
配置缺少我的要求.我覆盖了它默认的受支持的Mediatype
,它解决了这个问题.
I found the answer with help of @veeram and came to understand that my configuration for MappingJackson2HttpMessageConverter
were lacking as per my requirement. I override its default supported Mediatype
and it resolved the issue.
默认支持-
implication/json
application*/json
已完成代码更改以解决此问题-
Code change done to fix this case -
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.ALL);
jacksonMessageConverter.setSupportedMediaTypes(mediaTypes);
这篇关于如何为返回PDF文件的Spring Boot测试用例设置内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!