使用spring + spring,我必须自己连接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);
}当我想在我的测试中使用测试容器时,我还必须声明一个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)
但是,我的Context中有两个Contextbean,即使我只需要一个。
发布于 2021-05-06 07:10:23
https://github.com/wearearima/spring-data-jdbc-testcontainers上的示例似乎表明根本不需要定义您自己的DataSource。
请参见https://github.com/wearearima/spring-data-jdbc-testcontainers/blob/master/src/test/java/eu/arima/springdatajdbctestcontainers/AccountRepositoryTest.java#L94如何将TestContainers托管数据库的属性传递给Spring:
@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);
}https://stackoverflow.com/questions/67413169
复制相似问题