How to test DeferredResult timeoutResult

前端 未结 2 1602
醉梦人生
醉梦人生 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:41

    In my case, after going through spring source code and setting the timeout (10000 millisecond) and getting async result solved it for me, as;

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

    My whole test code was;

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

    Hope it helps..

    0 讨论(0)
  • 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());
    }
    
    0 讨论(0)
提交回复
热议问题