INSERT INTO bankdemo.bills(id, is_active, balance, currency, account_id)
VALUES('0', '1', '0.00', 'RUB', '0');
@Test
void can_change_bill_status() throws Exception {
mockMVC.perform(get("/bills/status/{id}", "0"))
.andExpect(status().isOk())
.andExpect(content().string(containsString("false")));
}
@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:未找到 id 为 0 的目标帐单
第 3 页测试的控制器内部方法使用 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();
可能是这样,但是如何正确测试这部分代码?
程序本身和使用模拟访问数据库的切片 @WebMvcTest 都很好。 春季启动 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>> futureOperations =
CompletableFuture.supplyAsync(() -> operationService.getAll(id), executorService);
好的,所以问题不在于 CompletableFuture,而在于使用 H2 数据库的 Spring Boot 测试的行为。 SQL 脚本奇怪地初始化数据,具体取决于它们在哪个阶段被调用(在启动期间或通过测试类或方法声明上面的 @SQL)。