0

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.

rmagarwal
  • 1
  • 4

2 Answers2

5

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())
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
zfChaos
  • 415
  • 4
  • 13
0

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.

marthursson
  • 3,242
  • 1
  • 18
  • 28
  • Yes, I tried that too as 'andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))' but then it gives error as content type not set. I tried setting content type in my REST API response header too but that also didn't work. – rmagarwal Aug 22 '16 at 10:51
  • That's not what I said. What you're doing is setting up an expectation on the response. You need to set up a precondition on the request: call `accept(MediaType.APPLICATION_OCTET‌​_STREAM)` on the `MockHttpServletRequestBuilder`, so that the appropriate accept header is populated. – marthursson Aug 22 '16 at 11:23
  • Yes, tried that too but still getting 406 error. mockMvc.perform( get(restUri).accept(MediaType.APPLICATION_OCTET_STREAM_VALUE)).andExpect(status().isOk()) – rmagarwal Aug 24 '16 at 05:00