MockMvcRequestBuilders.asyncDispatch提供空的HTTP响应和contentType

时间:2019-01-29 00:05:08

标签: java spring spring-mvc spring-test spring-test-mvc

我有一个单元测试,在尝试使用Spring 4.3将方法转换为返回 StreamingResponseBody 的方法之后,我试图检查发出的异步请求的响应。

测试方法如下:

final MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac)
     .apply(SecurityMockMvcConfigurers.springSecurity())
     .build();

MvcResult mvcResult1 = mockMvc.perform(
   get("/reports/generic/100?FIELD1=&FIELD3=").headers(STANDARD_HEADERS.get()))
  .andExpect(status().isOk())
  .andExpect(request().asyncStarted())
  .andReturn();

mvcResult1.getAsyncResult();

mockMvc.perform(asyncDispatch(mvcResult1))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType("text/csv"))
                    .andExpect(content().string("Test Data" + System.lineSeparator() + "FIELD1=" + System.lineSeparator() + "FIELD3=" + System.lineSeparator()))

它正在调用的方法如下:

public StreamingResponseBody streamReport(@PathVariable("type") @NotNull String type, @PathVariable("id") @NotNull Long id, ReportConfiguration config, HttpServletResponse response) throws Exception {


    ReportServiceHandler handler = reportHandlerFactory.getHandler(type);
    final String reportFilename = handler.getReportFileName(id, reportConfiguration);

    response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + reportFilename);
    response.setContentType("text/csv");

    return new StreamingResponseBody() {

        @Override
        public void writeTo(OutputStream outputStream) throws IOException {

            try {
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + reportFilename);
                response.setContentType("text/csv");
                ServletOutputStream out = (ServletOutputStream) outputStream;
                handler.generateReport(out, id, reportConfiguration);
                out.flush();
            } catch ( Exception e ) {
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline");
                response.setContentType("");
                throw new IOException(e);
            }
        }
    };
}

调试显示原始请求中包含来自异步的响应,但是在期间,复制了异步响应对象(在 mvcResult1 中) asyncDispatch ,因此contextType和content字符串均为null。

这里是否缺少处理异步mvcResult的测试配置,以便可以声明内容?

0 个答案:

没有答案