Tho*_*ang 3 spring-boot testcontainers spring-data-jdbc
使用 spring boot + spring data jdbc 我必须DataSource自己连接 bean。就像这样:
@Bean\n public DataSource dataSource() {\n HikariConfig hikariConfig = new HikariConfig();\n hikariConfig.setJdbcUrl(this.environment.getRequiredProperty("url"));\n hikariConfig.setUsername("user");\n hikariConfig.setDriverClassName("org.postgresql.Driver");\n hikariConfig.setPassword("password");\n return new HikariDataSource(hikariConfig);\n }\nRun Code Online (Sandbox Code Playgroud)\n当我想使用 testcontainers 进行测试时,我DataSource还必须声明一个 bean:
@Bean\n @Primary\n DataSource testDataSource() {\n\n if (POSTGRESQL_CONTAINER == null) {\n PostgreSQLContainer<?> container = new PostgreSQLContainer<>(DockerImageName.parse("postgres").withTag("9.6.12"));\n container.withInitScript("schema.sql");\n container.start();\n POSTGRESQL_CONTAINER = container;\n }\n PGSimpleDataSource dataSource = new PGSimpleDataSource();\n dataSource.setUrl(POSTGRESQL_CONTAINER.getJdbcUrl());\n dataSource.setUser(POSTGRESQL_CONTAINER.getUsername());\n dataSource.setPassword(POSTGRESQL_CONTAINER.getPassword());\n\n return dataSource;\n }\nRun Code Online (Sandbox Code Playgroud)\n使用我的测试,SpringBootTest我几乎必须使用ComponentScan所有包,因为我不想模拟所有其他 bean。
\n所以我的问题是:
\n我可以以某种方式排除主要DataSource测试用例吗?
\n(我当前的解决方法是将测试定义DataSource为Primary)
\n但是尽管如此,即使我只需要一个,我DataSource也有两个豆子。Context
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3368 次 |
| 最近记录: |