How to set content-type for a spring boot test case which returns PDF file

谁说我不能喝 提交于 2019-12-04 22:09:17

You have problem some where else. It appears that an exception/error occurred as noted by application/problem+json content type. This is probably set in the exception handler. As your client is only expecting application/pdf 406 is returned.

You can add a test case to read the error details to know what exactly the error is.

Something like

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. 

Going forward if you are expecting the error you can change the accept type to include both pdf and problem json type.

Note - This behaviors is dependent on the spring web mvc version you have.

The latest spring mvc version takes into account the content type header set in the response entity and ignores what is provided in the accept header and parses the response to format possible. So the same test you have will not return 406 code instead would return the content with application json problem content type.

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.

Default Supported -

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

406 means your client is asking for a contentType (probably pdf) that the server doesn't think it can provide.

I'm guessing the reason your code is working when you debug is that your rest client is not adding the ACCEPT header that asks for a pdf like the test code is.

To fix the issue, add to your @PostMapping annotation produces = MediaType.APPLICATION_PDF_VALUE see https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PostMapping.html#produces--

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!