问题描述
使用 spring boot + spring data jdbc,我必须自己连接 DataSource
bean。像这样:
@Bean
public DataSource dataSource() {
HikariConfig hikariConfig = new HikariConfig();
hikariConfig.setJdbcUrl(this.environment.getrequiredProperty("url"));
hikariConfig.setUsername("user");
hikariConfig.setDriverClassName("org.postgresql.Driver");
hikariConfig.setPassword("password");
return new HikariDataSource(hikariConfig);
}
当我想在测试中使用 testcontainers 时,我还必须声明一个 DataSource
bean:
@Bean
@Primary
DataSource testDataSource() {
if (POSTGREsql_CONTAINER == null) {
PostgresqlContainer<?> container = new PostgresqlContainer<>(DockerImageName.parse("postgres").withTag("9.6.12"));
container.withInitScript("schema.sql");
container.start();
POSTGREsql_CONTAINER = container;
}
PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setUrl(POSTGREsql_CONTAINER.getJdbcUrl());
dataSource.setUser(POSTGREsql_CONTAINER.getUsername());
dataSource.setPassword(POSTGREsql_CONTAINER.getpassword());
return dataSource;
}
将我的测试与 SpringBoottest
一起使用,我必须ComponentScan
几乎所有的包,因为我不想模拟所有其他 bean。
所以我的问题是:
我可以以某种方式排除主要的 DataSource
仅用于测试用例吗?
(我目前的解决方法是将测试 DataSource
定义为 Primary
)
但尽管如此,我的 DataSource
中有两个 Context
bean,即使我只需要一个。
解决方法
https://github.com/wearearima/spring-data-jdbc-testcontainers 处的示例似乎表明根本不需要定义自己的数据源。
参见https://github.com/wearearima/spring-data-jdbc-testcontainers/blob/master/src/test/java/eu/arima/springdatajdbctestcontainers/AccountRepositoryTest.java#L94如何将 TestContainers 托管数据库的属性传递给 Spring Boot:
@DynamicPropertySource
static void postgresqlProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url",postgresqlContainer::getJdbcUrl);
registry.add("spring.datasource.username",postgresqlContainer::getUsername);
registry.add("spring.datasource.password",postgresqlContainer::getPassword);
}