You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成测试异步线程查询DB出现实体找不到异常

问题描述
  • 在测试类上通过@Sql注解执行SQL,插入id为0的Bill数据:
INSERT INTO bankdemo.bills(id, is_active, balance, currency, account_id)
VALUES('0', '1', '0.00', 'RUB', '0');
  • 测试用例can_change_bill_status执行通过,说明id为0的Bill确实存在于数据库中:
@Test
void can_change_bill_status() throws Exception {
    
    mockMVC.perform(get("/bills/status/{id}", "0"))
        .andExpect(status().isOk())
        .andExpect(content().string(containsString("false")));
}
  • 但测试用例can_export_data_2_csv_file执行失败:
@Test
void can_export_data_2_csv_file() throws Exception {
    
    mockMVC.perform(get("/operations/print/{id}", "0"))
        .andExpect(status().isCreated())
        .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE));
}

抛出异常:CompletionException: EntityNotFoundException: Target bill with id: 0 not found

相关代码背景

该测试对应的控制器方法中,使用ThreadPoolTaskExecutor异步从数据库获取Bill:

CompletableFuture<BillResponseDTO> futureBill = CompletableFuture.supplyAsync
        (() -> {try {return billService.getBillDTO(id);}
                catch(EntityNotFoundException exc) {log.error(exc.getMessage(), exc);
                throw new CompletionException(exc);}
        }, executorService);
BillResponseDTO bill = futureBill.join();

程序本身运行正常,且使用Mock数据库访问的@WebMvcTest切片测试也没有问题,当前使用Spring Boot 2.6.6版本。

异步线程池配置

@Bean
@Primary
public Executor asyncExecutor() {
    final int cores = Runtime.getRuntime().availableProcessors();
    final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setCorePoolSize(cores);
    executor.setMaxPoolSize(cores * 2);
    executor.setQueueCapacity(cores * 10);
    executor.initialize();
    return executor;
}

同时,该控制器方法中另一个异步任务CompletableFuture<List<OperationResponseDTO>>未出现异常:

CompletableFuture<List<OperationResponseDTO>> futureOperations =
        CompletableFuture.supplyAsync(() -> operationService.getAll(id), executorService);

疑问

如何正确测试该部分代码?


内容的提问来源于stack exchange,提问作者V-CHO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 19:52:45