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