gpt4 book ai didi

java - 可以为每个 SpringbootTest 注解加载特定的 data.sql

转载 作者:行者123 更新时间:2023-12-02 04:15:26 26 4
gpt4 key购买 nike

我有多个@SpringBootTest测试,其中包含一个嵌入数据库(h2)和一个带有测试数据的data.sql。每个测试都有自己的域,并且随着 data.sql 变得越来越大。我想知道是否有任何选项可以为每个 @SpringBootTest 注释包含特定的 data.sql,例如属性源。

我知道有一个选项,即创建不同的application.properties并指定要加载的data.sql,但我想知道是否有是更清洁的选择。

目前我有这个:

@SpringBootTest(classes = {MyApplication.class}, webEnvironment = 
SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class MyFunctionalTest {

我想要这样的东西:

@SpringBootTest(classes = {MyApplication.class}, webEnvironment = 
SpringBootTest.WebEnvironment.RANDOM_PORT)
@ExtendWith(SpringExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@H2Data("sepecific.sql)
public class MyFunctionalTest {

最佳答案

嗨,在我看来,我可能已经为常规的 Spring Boot 应用程序完成了它,我还没有尝试过它用于测试,但我几乎确定它可以用于测试。您需要声明多个 DataSourceInitializers 就像我在这篇文章中所做的那样:

@Bean
public DataSourceInitializer dataSourceInitializer1(@Qualifier("datasource1") DataSource datasource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("schema-h22.sql"));
resourceDatabasePopulator.addScript(new ClassPathResource("data-h22.sql"));

DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(datasource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}

@Bean
public DataSourceInitializer dataSourceInitializer2(@Qualifier("datasource2") DataSource datasource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("schema-h21.sql"));
resourceDatabasePopulator.addScript(new ClassPathResource("data-h21.sql"));

DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(datasource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}

Spring Boot 2 Multiple Datasources initialize schema

关于java - 可以为每个 SpringbootTest 注解加载特定的 data.sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662861/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com