Spring Asyncronous post 请求的单元测试返回异常(异步开始预期为真但假)

ana*_*and 6 junit asynchronous mockito spring-boot mockmvc

我的 POST 请求是异步的,因为我使用的是 spring-data-rest。现在我在尝试为 POST 请求编写测试用例时遇到问题。例外是“异步开始预期:真但为:假”

我读过很多文章,他们都说如何为异步 GET 方法而不是 POST 方法做一个测试用例。我正在尝试为 GET 方法实现这些文章中建议的逻辑,但收到异常。

private final MediaType contentType = new 
MediaType(MediaType.APPLICATION_JSON.getType(),
        MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

private MockMvc mockMvc;

@Autowired
private WebApplicationContext webApplicationContext;    


@Test
public void addProgramToTestDefaultValuesUsingAsync() throws Exception {

    UserProgram request = getProgramRequest();

    MvcResult result = mockMvc.perform(post("/programs")
            .content(TestUtils.asJsonString(request))
            .contentType(contentType))
            .andDo(print())
            .andExpect(request().asyncStarted())
            .andReturn();

    mockMvc.perform(asyncDispatch(result))
            .andExpect(status().isCreated())
            .andExpect(header().string(CONTENT_TYPE, APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("programRetries").value("3"));
}
Run Code Online (Sandbox Code Playgroud)

我期待它等到调用完成,然后想根据异常值检查响应。但是调用在 request().asyncStarted() 失败,它返回“Async started expected: true but was: false”。我已经阅读了很多文章,但没有解决这个问题。任何帮助表示赞赏。

为了构建我的测试用例,我使用了以下文章:

https://niels.nu/blog/2016/spring-async-rest.html

http://callistaenterprise.se/blogg/teknik/2014/06/23/testing-non-blocking-rest-services-with-spring-mvc-and-spring-boot/

小智 0

我也有同样的问题。如果您正在尝试测试控制器 api,请尝试执行以下操作,看看它是否适合您:

mockMvc = MockMvcBuilders.standaloneSetup(new UserApi(new ServiceUser()).setAsyncRequestTimeout(1000).build();
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。