我有这样的代码
@RequestMapping(value = "/create", method = RequestMethod.POST)
public Result createModel(DataModel model) {
CompletableFuture.runAsync(() -> doSomeThing(model));
return new Result("your request has been recieved successfully");
}
我尝试编写集成测试,例如
@RunWith(SpringJUnit4ClassRunner.class)
@@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("integration_tests, linux")
@Transactional
public class DataServiceTestIT {
@AutoWired
private WebApplicationContext wac;
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
this.mockMvc.perform(post('/create')).andExcpect(status().isOk());
assertEquals(1, JdbcTestUtil.countRowsInTable(jdbcTemplate, "data_model_table));
}
当后台收到请求时,会立即响应成功的消息,异步处理实际作业。发送响应后,服务器停止,我无法测试doSomeThing代码。(我的真实代码比较复杂,有多个异步部分(
如何防止服务器停止或等待其他方法的改进。我的控制器不返回可调用结果。处理完成后,向用户发送通知。我尝试使用 get MvcResult.getAsyncResult((,但我认为它不适合这个。
为了等待完成方法,我使用 CompletableFuture 和 doAnswer 和 callRealMethod。
@AutoWired
private WebApplicationContext wac;
@SpyBean
private DoSomethingService doSomethingService;
@Test
public void test() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
CompletableFuture<String> cf = new CompletableFuture<>();
doAnswer((invocation) -> {
invocation.callRealMethod();
cf.complete("method finished");
return null;
}).when(doSomethingService).doSomethingMetod();
this.mockMvc.perform(post('/create')).andExcpect(status().isOk());
cf.get(TIME_OUT, TimeUnit.MILLISECONDS);
assertEquals(1, JdbcTestUtil.countRowsInTable(jdbcTemplate,
"data_model_table));
}