我有一个带有 @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/