Spring MVC测试框架为异步控制器测试返回不一致的结果

时间:2013-08-05 08:30:05

标签: java testing spring-mvc asynchronous

使用Spring MVC测试框架standaloneSetup模式来测试异步方法调用,我得到了不一致的结果。以下测试可以在我的IDE中传递,但在使用ANT运行时失败,但有时在使用ANT运行时会通过,或者在IDE中失败。第二个调用的内容将只返回并清空字符串,或返回预期的响应。

如果我在第一次调用中添加.andDo(print),或者在2次mockMvc.perform调用之间添加500ms的Sleep,则测试将通过。

还有其他人遇到过这个吗?

控制器路线

@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);
        }
    };
}

测试

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("[]"));
}

3 个答案:

答案 0 :(得分:3)

您需要调用asyncStarted

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

虽然这对我来说仍然有不一致的结果

答案 1 :(得分:2)

它帮助我调用虚拟

mvcResult.getAsyncResult();

在检查结果之前。否则我得到响应200而不是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());

答案 2 :(得分:1)

spring mvc test framework https://jira.springsource.org/browse/SPR-10838已知错误。

尝试2.3.5-SNAPSHOT,似乎在那里修复了

相关问题