java - 如何在组件初始化之前在Spring Boot测试中加载h2数据

标签 java spring spring-boot tdd integration-testing

我有一个带有 @Scheduled 方法的 @Component,该方法每 x 分钟运行一次(固定延迟) 在运行我的集成 @SpringBootTest 时,该组件使用应用程序上下文进行初始化,然后执行我的测试方法

调度程序定期轮询数据库并执行一些逻辑。因此,一旦加载了应用程序上下文,就需要在 h2 数据库中预加载数据

@Component
public class MyScheduler {
   ...
   ...
    @Scheduled(fixedDelayString = "${poll.interval:300}")
    public void testXYZ() throws Exception {
        dbService.fetchRecords();
        //do blah blah
    }
}

如何在加载 @SpringBootTest 应用程序上下文之前在 h2 中预加载初始数据?

一旦服务出现在我的集成测试中,我想根据一些 @Scheduled 定期运行来执行数据断言

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MyIntegrationTest{

    ...

    @Test
    @Sql(scripts={"classpath:data/data.sql"}, 
    config=@SqlConfig(transactionMode = TransactionMode.ISOLATED), 
    executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
    testMySchedulerLogic() {
        assertTrue(isProcessed(), true);
    }
}

最佳答案

使用您需要的数据在测试资源中创建 import.sql 文件。

In addition, a file named import.sql in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the ddl-auto property is set to create or create-drop). This can be useful for demos and for testing if you are careful but is probably not something you want to be on the classpath in production. It is a Hibernate feature (and has nothing to do with Spring).

来源:https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

关于java - 如何在组件初始化之前在Spring Boot测试中加载h2数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49512239/

相关文章:

spring boot 数据 cassandra 响应式(Reactive) JmxReporter 问题

java - 在每个查询中实例化一个新的 JdbcTemplate 还是在所有地方注入(inject)一个更好?

java - spring中的数组依赖注入(inject)?

java - 为 Spring Boot 应用程序部署新功能的最佳实践是什么?

spring-boot - 是否可以将 Spring Boot 应用程序部署到 App Engine 并连接到数据库?

java - MemoryPoolMXBean.getUsage() 相对于 Runtime.freeMemory() 的优势

java - 如何在我的项目中正确配置 Spring Security?

java - 带有 Zuul 的 Spring Boot 2.4.2 网关 API

Java FixThreadPool 无法设置池大小?

java - Seam-Gen、Netbeans 和完成