Spring Boot 如何在由Junit5启动并由Sping Boot 配置的测试容器内创建PostgresQL扩展

qf9go6mv  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(79)

我有一个Sping Boot 3项目,在那里我编写了使用测试容器运行PostgreSQL数据库的集成测试。我想在一个端点中引入模糊匹配,因此需要PostgresQL扩展pg_trgm。
此外,我阅读了文档,但仍然不清楚我应该如何做这样的事情。

按照我在一些GitHub issue中发现的,我尝试在测试配置中定义一个bean,但testcontainer似乎并不关心:

@TestConfiguration(proxyBeanMethods = false)
public class DatabaseConfiguration {

    @Bean
    public PostgreSQLContainer<?> postgreSQLContainer() {
        var name = DockerImageName
                .parse("localhost/cadonym/database")
                .asCompatibleSubstituteFor("postgres");
        return new PostgreSQLContainer<>(name);
    }
}

字符串
其中图像由以下定义:

# This image is meant to be used during development only.
FROM docker.io/library/postgres:15.3

ENV POSTGRES_USER=postgres
ENV POSTGRES_PASSWORD=postgres
ENV POSTGRES_DB=cadonym

RUN echo "CREATE EXTENSION pg_trgm" >> /docker-entrypoint-initdb.d/pg_trgm.sql


在运行我的测试时,我可以看到testcontainer正在创建基于docker.io/testcontainers/ryuk:0.5.1docker.io/library/postgres:15.1的容器。没有使用自定义镜像,尽管我的测试配置:“函数相似性(字符变化,字符变化)不存在”,但测试行为没有改变。
我通过将调用“asumbleSubstituteFor”(“postgres”)的参数更改为随机值来验证我的配置是否已加载,并且它确实已加载,因为上述更改会阻止上下文按预期加载。
其他相关配置可以在我的测试属性中找到:

spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver
spring.datasource.url=jdbc:tc:postgresql:15.1:///integration-tests-db

pn9klfpd

pn9klfpd1#

缺少的部分是注解@ServiceConnection:

package dev.fita.cadonym;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.context.annotation.Bean;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.utility.DockerImageName;

@TestConfiguration(proxyBeanMethods = false)
public class DatabaseConfiguration {

    @Bean
    @ServiceConnection
    public static PostgreSQLContainer<?> postgreSQLContainer() {
        return new PostgreSQLContainer<>(DockerImageName
                .parse("localhost/cadonym/database")
                .asCompatibleSubstituteFor("postgres"))
                .withUsername("api")
                .withDatabaseName("cadonym");
    }

}

字符串

相关问题