这里我转换的方法与以前具有相同的响应签名,但不是立即响应,它现在使用长轮询:
private Map<String, DeferredResult<ResponseEntity<?>>> requests = new ConcurrentHashMap<>();
@RequestMapping(value = "/{uuid}", method = RequestMethod.GET)
public DeferredResult<ResponseEntity<?>> poll(@PathVariable("uuid") final String uuid) {
// Create & store a new instance
ResponseEntity<?> pendingOnTimeout = ResponseEntity.accepted().build();
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(TWENTYFIVE_SECONDS, pendingOnTimeout);
requests.put(uuid, deferredResult);
// Clean up poll requests when done
deferredResult.onCompletion(() -> {
requests.remove(deferredResult);
});
// Set result if already available
Task task = taskHolder.retrieve(uuid);
if (task == null)
deferredResult.setResult(ResponseEntity.status(HttpStatus.GONE).build());
else
// Done (or canceled): Redirect to retrieve file contents
if (task.getFutureFile().isDone())
deferredResult.setResult(ResponseEntity.created(RetrieveController.uri(uuid)).build());
// Return result
return deferredResult;
}
特别是当请求花费太长时间(我之前立即返回)时,我想返回pendingOnTimeout
响应,以防止代理切断请求。
现在我想我已经按原样工作了,但我想写一个单元测试来证实这一点。然而,我所有使用 MockMvc(通过 webAppContextSetup)的尝试都未能为我提供一种断言我得到一个accepted
标题的方法。例如,当我尝试以下操作时:
@Test
public void pollPending() throws Exception {
MvcResult result = mockMvc.perform(get("/poll/{uuid}", uuidPending)).andReturn();
mockMvc.perform(asyncDispatch(result))
.andExpect(status().isAccepted());
}
我得到以下堆栈跟踪:
java.lang.IllegalStateException:处理程序 [public org.springframework.web.context.request.async.DeferredResult> nl.bioprodict.blast.api.PollController.poll(java.lang.String)] 的异步结果未设置在 org.springframework.test.web.servlet.DefaultMvcResult.getAsyncResult(DefaultMvcResult.java:143) 在 org.springframework.test.web 的 org.springframework.util.Assert.state(Assert.java:392) 指定 timeToWait=25000 .servlet.DefaultMvcResult.getAsyncResult(DefaultMvcResult.java:120) 在 org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch(MockMvcRequestBuilders.java:235) 在 nl.bioprodict.blast.docs.PollControllerDocumentation.pollPending(PollControllerDocumentation .java:53) ...
与此相关的 Spring 框架测试似乎都在使用模拟:https ://github.com/spring-projects/spring-framework/blob/master/spring-web/src/test/java/org/springframework /web/context/request/async/WebAsyncManagerTimeoutTests.java
如何测试 DeferredResult timeoutResult 的正确处理?