【问题标题】:406 error while mocking File Download REST API using MockMVC使用 MockMVC 模拟文件下载 REST API 时出现 406 错误
【发布时间】:2016-08-22 10:28:02
【问题描述】:

我正在使用 Spring 框架实现一个 REST API,它返回

return new ResponseEntity<>(new InputStreamResource(myInputStream),
                responseHeaders, HttpStatus.OK);

REST API 声明为:

@RequestMapping(value = "/download", method = RequestMethod.GET, 
produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE })

在为此 API 编写单元测试时,我正在使用 MockMVC,如下所示:

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

我的测试用例是这样的:

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

但我的状态为错误 406。

java.lang.AssertionError: Status expected:<200> but was:<406>
at org.springframework.test.util.AssertionErrors.fail

我在这里缺少什么? 任何帮助将不胜感激。

【问题讨论】:

    标签: spring rest unit-testing spring-mvc mockmvc


    【解决方案1】:

    您将MappingJackson2HttpMessageConverter 的实例注入MockMvcBuilders,它无法处理转换从Resource 继承的类。您需要做的就是将ResourceHttpMessageConverter 添加到您的测试规范中:

    MockMvcBuilders.standaloneSetup(myController)
    .setMessageConverters(messageConverter, new ResourceHttpMessageConverter())
    

    【讨论】:

      【解决方案2】:

      状态码 406 表示“不可接受”,这表明服务器缺少指定可接受内容类型的标头。您需要将其包含在您的 mockMvc 调用中。

      【讨论】:

      • 是的,我也尝试过 'andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))' 但由于未设置内容类型,它会给出错误。我也尝试在我的 REST API 响应标头中设置内容类型,但这也没有用。
      • 我不是这么说的。您正在做的是对响应设定期望。您需要对请求设置一个先决条件:在MockHttpServletRequestBuilder 上调用accept(MediaType.APPLICATION_OCTET‌​_STREAM),以便填充适当的接受标头。
      • 是的,也尝试过,但仍然出现 406 错误。 mockMvc.perform(get(restUri).accept(MediaType.APPLICATION_OCTET_STREAM_VALUE)).andExpect(status().isOk())
      猜你喜欢
      • 2015-09-17
      • 1970-01-01
      • 2019-11-05
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多