16

我正在根据一段时间前的 Spring 博客实施长轮询

这里我转换的方法与以前具有相同的响应签名,但不是立即响应,它现在使用长轮询:

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 的正确处理?

4

2 回答 2

13

就我而言,在通过spring源代码并设置超时(10000毫秒)并获得异步结果后为我解决了它,如;

 mvcResult.getRequest().getAsyncContext().setTimeout(10000);
 mvcResult.getAsyncResult();

我的整个测试代码是;

MvcResult mvcResult = this.mockMvc.perform(
                                post("<SOME_RELATIVE_URL>")
                                .contentType(MediaType.APPLICATION_JSON)
                                .content(<JSON_DATA>))
                        ***.andExpect(request().asyncStarted())***
                            .andReturn();

***mvcResult.getRequest().getAsyncContext().setTimeout(10000);***
***mvcResult.getAsyncResult();***

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

希望能帮助到你..

于 2017-07-11T11:20:41.670 回答
6

我使用 Spring 4.3遇到了这个问题,并设法找到了一种从单元测试中触发超时回调的方法。获取后MvcResult,调用前asyncDispatch(),可以插入如下代码:

MockAsyncContext ctx = (MockAsyncContext) mvcResult.getRequest().getAsyncContext();
for (AsyncListener listener : ctx.getListeners()) {
    listener.onTimeout(null);
}

请求的异步侦听器之一将调用DeferredResult的超时回调。

所以你的单元测试看起来像这样:

@Test
public void pollPending() throws Exception {
    MvcResult result = mockMvc.perform(get("/poll/{uuid}", uuidPending)).andReturn();
    MockAsyncContext ctx = (MockAsyncContext) result.getRequest().getAsyncContext();
    for (AsyncListener listener : ctx.getListeners()) {
        listener.onTimeout(null);
    }
    mockMvc.perform(asyncDispatch(result))
            .andExpect(status().isAccepted());
}
于 2018-07-27T19:20:12.933 回答