How to test DeferredResult timeoutResult

前端 未结 2 1603
醉梦人生
醉梦人生 2020-12-10 12:27

I\'m implementing long polling as per the Spring blog from some time ago.

Here my converted method with same response signature as before, but instead of responding

2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-10 12:56

    I ran across this problem using Spring 4.3, and managed to find a way to trigger the timeout callback from within the unit test. After getting the MvcResult, and before calling asyncDispatch(), you can insert code such as the following:

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

    One of the async listeners for the request will invoke the DeferredResult's timeout callback.

    So your unit test would look like this:

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

提交回复
热议问题