简体   繁体   中英

Spring MVC test framework returning inconsistent results for async controller tests

Using Spring MVC test frameworks standaloneSetup mode to test asynchronous methods calls, I'm getting inconsistent results. The following test can pass in my IDE, but then fail when run using ANT, but then at times will pass when run using ANT, or fail in the IDE. The contents of the second call will just return and empty string, or return the expected response.

If I add .andDo(print) to the first call, or add a Sleep of say 500ms between the 2 mockMvc.perform calls, the test will pass.

Has anybody else encountered this?

Controller Route

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public final Callable<ResponseEntity<List<Integer>>> getEntries(
        @RequestParam(value = "limit", defaultValue = "100") final int limit) {
    return new Callable<ResponseEntity<List<Integer>>>() {
        @Override
        public ResponseEntitcany<List<Integer>> call() {
            return new ResponseEntity<List<Integer>>(service.findTopEntries(limit), HttpStatus.OK);
        }
    };
}

Test

this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();

@Test
public void testJSONResponse() throws Exception {

    MvcResult mvcResult = this.mockMvc.perform(get(this.basePath)
            .accept(MediaType.APPLICATION_JSON))
            .andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult))
            .andExpect(status().isOk())
            .andExpect(content().string("[]"));
}

You need to call asyncStarted

MvcResult mvcResult = this.mockMvc.perform(get(this.basePath)
        .accept(MediaType.APPLICATION_JSON)).andExpect(request().asyncStarted())
        .andReturn();

Though this still gave inconsistent results at times for me

It helped me to invoke dummy

mvcResult.getAsyncResult();

before checking the result. Otherwise I get response 200 instead of 404. Spring 4.0.6.

        final MvcResult mvcResult = this.mockMvc.perform(get("/api/buildings/{id}", key.toString())
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(request().asyncStarted())
            .andReturn();
        mvcResult.getAsyncResult();

        this.mockMvc.perform(asyncDispatch(mvcResult))
            .andDo(print())
            .andExpect(status().isNotFound());

There is known bug in spring mvc test framework, https://jira.springsource.org/browse/SPR-10838 .

Try 2.3.5-SNAPSHOT, It seems to be fixed there

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM