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

qf9go6mv  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(162)

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

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

  1. @TestConfiguration(proxyBeanMethods = false)
  2. public class DatabaseConfiguration {
  3. @Bean
  4. public PostgreSQLContainer<?> postgreSQLContainer() {
  5. var name = DockerImageName
  6. .parse("localhost/cadonym/database")
  7. .asCompatibleSubstituteFor("postgres");
  8. return new PostgreSQLContainer<>(name);
  9. }
  10. }

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

  1. # This image is meant to be used during development only.
  2. FROM docker.io/library/postgres:15.3
  3. ENV POSTGRES_USER=postgres
  4. ENV POSTGRES_PASSWORD=postgres
  5. ENV POSTGRES_DB=cadonym
  6. 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”)的参数更改为随机值来验证我的配置是否已加载,并且它确实已加载,因为上述更改会阻止上下文按预期加载。
其他相关配置可以在我的测试属性中找到:

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

pn9klfpd

pn9klfpd1#

缺少的部分是注解@ServiceConnection:

  1. package dev.fita.cadonym;
  2. import org.springframework.boot.test.context.TestConfiguration;
  3. import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
  4. import org.springframework.context.annotation.Bean;
  5. import org.testcontainers.containers.PostgreSQLContainer;
  6. import org.testcontainers.utility.DockerImageName;
  7. @TestConfiguration(proxyBeanMethods = false)
  8. public class DatabaseConfiguration {
  9. @Bean
  10. @ServiceConnection
  11. public static PostgreSQLContainer<?> postgreSQLContainer() {
  12. return new PostgreSQLContainer<>(DockerImageName
  13. .parse("localhost/cadonym/database")
  14. .asCompatibleSubstituteFor("postgres"))
  15. .withUsername("api")
  16. .withDatabaseName("cadonym");
  17. }
  18. }

字符串

展开查看全部

相关问题