集成测试的奇怪问题

问题描述 投票:0回答:1
  1. @Sql 在测试类
INSERT INTO bankdemo.bills(id, is_active, balance, currency, account_id)
VALUES('0', '1', '0.00', 'RUB', '0');
  1. 绿色测试显示 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")));
    }
  1. 但是下一个突然失败了
    @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);
spring-boot h2 spring-boot-test completable-future mockmvc
1个回答
0
投票

好的,所以问题不在于 CompletableFuture,而在于使用 H2 数据库的 Spring Boot 测试的行为。 SQL 脚本奇怪地初始化数据,具体取决于它们在哪个阶段被调用(在启动期间或通过测试类或方法声明上面的 @SQL)。

© www.soinside.com 2019 - 2024. All rights reserved.