spring开机测试组件初始化前如何加载h2数据

How to load h2 data in spring boot test before component initialization

我有一个 @Component 和 @Scheduled 方法,它每 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