gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:17:26 26 4
gpt4 key购买 nike

我需要测试一个调用异步服务的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com