spring-mvc - MockMVC 对异步服务执行后期测试

标签 spring-mvc asynchronous mocking async-await mockito

我需要测试一个调用异步服务的 Controller 。

Controller 代码

@RequestMapping(value = "/path", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Result> massiveImport(HttpServletRequest request) {
    try {
        service.asyncMethod(request);
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity<>(new Result(e.getMessage()), HttpStatus.BAD_REQUEST);
    }

    return new ResponseEntity<>(new Result(saveContact.toString()), HttpStatus.OK);
}

服务代码
@Async
public Future<Integer> asyncMethod(HttpServletRequest request) throws IllegalFieldValueException, Exception {
    ...
    return new AsyncResult<>(value);
}

测试代码
MvcResult result = getMvc().perform(MockMvcRequestBuilders.fileUpload("/path/")
                           .header("X-Auth-Token", accessToken)
                           .accept(MediaType.APPLICATION_JSON))
                           .andDo(print())
                           .andReturn();

测试没问题。但是我会在关闭测试之前等待完成异步服务。

有没有办法做到这一点?

最佳答案

如果您只想等待异步执行完成,请查看 MvcResult .您可以通过 getAsyncResult() 等待.

使用您当前的代码,您只是在没有任何断言的情况下执行请求。所以测试是不完整的。对于完整的测试,需要以下两个步骤。

首先执行请求:

MvcResult mvcResult = getMvc().perform(fileUpload("/path/")
                              .header("X-Auth-Token", accessToken)
                              .accept(MediaType.APPLICATION_JSON))
                              .andExpect(request().asyncStarted())
                              .andReturn();

然后通过 asyncDispatch 启动异步调度并执行断言:
getMvc().perform(asyncDispatch(mvcResult))
        .andExpect(status().isOk())
        .andExpect(content().contentType(...))
        .andExpect(content().string(...));

关于spring-mvc - MockMVC 对异步服务执行后期测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42069226/

相关文章:

spring-mvc - 一个 Controller 方法中的多个 @RequestBody 值

javascript - 自耕农生成器 : copy or template doesn't work from inside async callback

python : efficiency concerns in parallel async calls to fetch data from web services

unit-testing - 在测试中什么是经过验证的假货?

spring-mvc - Controller 上的 Spring Security @PreAuthorize

java - Spring MVC 3.2.5 无法识别的字段 jackson

facebook - 使用 Spring Social 登录 Facebook 和 Twitter

javascript - loadasync 函数导入的外部脚本什么时候执行?

testing - 为什么模拟测试框架有帮助?

python 响应 - 并非所有请求都已执行