MockMVC 对异步服务执行后期测试 [英] MockMVC perform post test to async service

查看:29
本文介绍了MockMVC 对异步服务执行后期测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试一个调用异步服务的控制器.

I need to test a controller which calls an asynchronous service.

控制器代码

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

测试正常.但我会在结束测试之前等待完成异步服务.

Test is ok. But I would wait, before closing the test, to complete async service.

有什么办法吗?

推荐答案

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

If you just want to wait for the async execution to be finished have look at MvcResult. You can wait for it with getAsyncResult().

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

With your current code you are just performing the request without any assertions. So the test is not complete. For a complete test it takes the following two steps.

首先执行请求:

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

然后通过 asyncDispatch 并执行断言:

Then start the async dispatch via asyncDispatch and perform assertions:

getMvc().perform(asyncDispatch(mvcResult))
        .andExpect(status().isOk())
        .andExpect(content().contentType(...))
        .andExpect(content().string(...));

这篇关于MockMVC 对异步服务执行后期测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆