首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spring数据JDBC测试容器DataSource

Spring数据JDBC测试容器DataSource
EN

Stack Overflow用户
提问于 2021-05-06 06:52:14
回答 1查看 1.5K关注 0票数 0

使用spring + spring,我必须自己连接DataSource bean。就像这样:

代码语言:javascript
复制
@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:

代码语言:javascript
复制
@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,即使我只需要一个。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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:

代码语言:javascript
复制
 @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);
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67413169

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档