Spring asynch method integration test fails

2019-08-27 12:10发布

问题:

I created an integration test for asynchronous rest controller method. Which looks like:

   @Test
    public void shouldHandleRequestsAsynchronously() throws Exception {
        MvcResult mvcResult = this.mockMvc.perform(get("/api/reports/daily?startDate=2004-04-13&endDate=2005-04-13"))
                .andExpect(request().asyncStarted())
                .andReturn();

        this.mockMvc.perform(asyncDispatch(mvcResult))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$[0].totalDistance", equalTo(100)))
                .andExpect(jsonPath("$[0].totalPrice", equalTo(100.7)));
    }

The main problem is, that all the time I am getting the assertion error:

java.lang.AssertionError: Async started 
Expected :true
Actual   :false

At line with .andExpect(request().asyncStarted().To be honest I don't have any idea what is wrong.

My rest controller method is:

@GetMapping(value = "/daily")
public ResponseEntity<List<DailyReport>> getDailyReports(
        @PathParam("startDate") @DateTimeFormat(pattern = "YYYY-MM-DD") Date startDate,
        @PathParam("endDate") @DateTimeFormat(pattern = "YYYY-MM-DD") Date endDate) throws InterruptedException, ExecutionException {
    return new ResponseEntity<>(reportService.findReports(startDate, endDate).get(), HttpStatus.OK);
}

Do you have any idea what could be wrong?

回答1:

So,

I read documentation once again and I sort this problem out. If you want to use method request().asyncStarted(), you have to wrap your response Callable or DeferredResult.

  • Assert whether asynchronous processing started, usually as a result of a controller method returning {@link Callable} or {@link DeferredResult}.