gpt4 book ai didi

testcontainers - 如何在 TestContainers 中创建数据库?

转载 作者:行者123 更新时间:2023-12-02 04:31:31 26 4
gpt4 key购买 nike

我正在使用此依赖项:

<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>

这是容器,通过我的测试启动:
@ClassRule
public static PostgreSQLContainer postgres = new PostgreSQLContainer()
.withDatabaseName("user")
.withUsername("postgres")
.withPassword("postgres");

但是当我试图建立与数据库的连接时 user我收到异常:
PSQLException: FATAL: database "user" does not exist

在此容器中仅存在默认数据库 "postgres" .

如何创建数据库 "user" ?

最佳答案

问题是因为容器返回带有随机端口的 JDBC_URL,并且默认端口可访问默认 Postgres DB,但您需要一个在随机端口上

这是解决方法:

@ClassRule
public static DockerComposeContainer environment =
new DockerComposeContainer(new File("src/test/resources/docker-compose-postgres.yml"))
.withExposedService("postgres-it", 5432);

这是 docker-compose yml:
version: "2"
services:
postgres-it:
image: postgres
ports:
- 5432:5432
hostname: postgres-it
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: user

关于testcontainers - 如何在 TestContainers 中创建数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com