【问题标题】:Spring Data JDBC Testcontainers DataSourceSpring Data JDBC 测试容器数据源
【发布时间】:2021-07-28 11:26:10
【问题描述】:

使用 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
但是我的Context 中有两个DataSource bean,即使我只需要一个。

【问题讨论】:

  • 这能回答你的问题吗? exclude @Component from @ComponentScan
  • 谢谢。我会试试这个。顺便一提。您是否在下面查看了 Wim Deblauwe 的答案?此代码中没有声明专用的DataSource。这在 Spring Data JDBC 中不是必须的吗?我只是好奇......
  • Spring Boot 可以创建您的数据源,这似乎与 Wims 答案一起使用,其中在动态属性源中配置了必要的信息。

标签: spring-boot testcontainers spring-data-jdbc


【解决方案1】:

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 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);
    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-09-29
  • 2020-03-16
  • 1970-01-01
  • 2016-09-14
  • 2015-01-01
  • 2017-07-17
  • 2018-03-22
  • 1970-01-01
相关资源
最近更新 更多