How to load properties dynamically to application testcontainer?

242 Views Asked by At

I am trying to make an integration test of a Java application that uses a jdbc postgres connection.

In the integration test i spawn two testcontainers, an application one and a postgres one.

How can i inject in the application the postgresDB.getJdbcUrl()?

Currently I have a datasource.properties file that the application uses for the jdbc connection.

In integration test folder i have another datasource-test.properties file that is loaded to the application testcontainer.

The datasource-test.properties is created dynamically after the postgres testcontainer is started but the application container starts before the dynamic creation of the datasource-test.properties.

Can i use this approach? How to load properties file in testcontainer after another testcontainer creates this file?

If not I need something similar to @DynamicPropertySource that Spring Boot has but my application is not Spring.

1

There are 1 best solutions below

0
On

There are two things to consider in this case. Both containers should be in the same network so they can talk with each other and the application container should wait on postgres container due it is a dependency. In the example below you can see a draft of how to work with those.

Network network = Network.newNetwork();

PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15")
    .withNetwork(network)
    .withNetworkAliases("postgres");

GenericContainer<?> app = new GenericContainer<>("my-app:0.0.1")
    .withNetwork(network)
    .withExposedPorts(8080)
    .dependsOn(postgres);

postgres.start();
app.start();

When creating the application container, jdbc:postgresql://postgres:5432/test can be used because now that both containers are in the same network they can talk to each other using the network aliases and also we can use postgres' port 5432 directly instead of the random port.

NOTE: PostgreSQLContainers is still exposing a random port for 5432 but that should be used when you want to test against the database, which is not the case due the the goal is to test the containerized application which communicates with the database.