I am implementing a REST API using Spring framework, which returns
return new ResponseEntity<>(new InputStreamResource(myInputStream),
responseHeaders, HttpStatus.OK);
REST API is declared as:
@RequestMapping(value = "/download", method = RequestMethod.GET,
produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
While writing unit test for this API, I am using MockMVC like below:
final MappingJackson2HttpMessageConverter messageConverter =
new MappingJackson2HttpMessageConverter();
messageConverter.setObjectMapper(new ObjectMapper());
messageConverter.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
this.mockMvc =
MockMvcBuilders.standaloneSetup(myController)
.setMessageConverters(messageConverter)
.apply(new RestDocumentationConfigurer()
.withScheme("https").withHost("localhost")
.withPort(443)).build();
And my Test case looks like this:
mockMvc.perform(
org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.get(restUri))
.andExpect(
org.springframework.test.web.servlet.result.MockMvcResultMatchers
.status().isOk())
.andDo(document("myApi")).andReturn();
But I am getting status as error 406.
java.lang.AssertionError: Status expected:<200> but was:<406>
at org.springframework.test.util.AssertionErrors.fail
What I am missing here? Any help would be much appreciated.
You inject instance of MappingJackson2HttpMessageConverter
to MockMvcBuilders
which can't deal with converting classes inheriting from Resource
. All you need to do is add ResourceHttpMessageConverter
to your test specification:
MockMvcBuilders.standaloneSetup(myController)
.setMessageConverters(messageConverter, new ResourceHttpMessageConverter())
Status code 406 means "Not Acceptable", which indicates that the server is missing a header specifying an accepted content type. You'll need to include that in your mockMvc call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.