[英]Spring MVC test framework returning inconsistent results for async controller tests
使用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("[]"));
}
您需要致电asyncStarted
MvcResult mvcResult = this.mockMvc.perform(get(this.basePath)
.accept(MediaType.APPLICATION_JSON)).andExpect(request().asyncStarted())
.andReturn();
虽然这有时仍然给我带来不一致的结果
它帮助我调出假人
mvcResult.getAsyncResult();
在检查结果之前。 否则,我得到响应200而不是404。Spring4.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());
spring mvc测试框架https://jira.springsource.org/browse/SPR-10838中存在一个已知的错误。
尝试2.3.5-SNAPSHOT,它似乎在那里固定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.