使用 Spring MVC 测试框架 standaloneSetup 模式测试异步方法调用,我得到不一致的结果。以下测试可以在我的 IDE 中通过,但在使用 ANT 运行时会失败,但在使用 ANT 运行时有时会通过,或者在 IDE 中会失败。第二次调用的内容将只返回空字符串,或者返回预期的响应。
如果我将 .andDo(print) 添加到第一个调用,或者在 2 个 mockMvc.perform 调用之间添加一个 500 毫秒的 sleep ,测试将通过。
有没有人遇到过这个?
Controller 路由
@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("[]"));
}
最佳答案
你需要调用asyncStarted
MvcResult mvcResult = this.mockMvc.perform(get(this.basePath)
.accept(MediaType.APPLICATION_JSON)).andExpect(request().asyncStarted())
.andReturn();
虽然这对我来说有时仍然会产生不一致的结果
关于java - Spring MVC 测试框架为异步 Controller 测试返回不一致的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18053703/