Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create database in TestContainers?

I'm using this dependency:

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

this is the Container, lauched with my tests:

@ClassRule
public static PostgreSQLContainer postgres = new PostgreSQLContainer()
    .withDatabaseName("user")
    .withUsername("postgres")
    .withPassword("postgres");

but when i'm trying to stablish connection to database user i'm receiving exception:

PSQLException: FATAL: database "user" does not exist

In this container only present default DB "postgres".

How to create database "user"?

like image 410
Igor Avatar asked Nov 08 '22 11:11

Igor


1 Answers

The problem was because container return JDBC_URL with random port, and by the default port is accessible default Postgres DB, but thee neede one is on random port

this is the workaround:

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

this is the 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
like image 83
Igor Avatar answered Dec 01 '22 23:12

Igor