In my Spring Boot 2.4.3 application I use Testcontainers and I followed the instructions found on the internet. I have an application.yaml
:
spring:
datasource:
url: jdbc:tc:postgresql:13.2:///testdb?TC_INITSCRIPT=tc_initscript_postgresql.sql
username: duke
password: s3crEt
jpa:
database-platform: org.hibernate.dialect.PostgreSQL95Dialect
hibernate:
ddl-auto: create-drop
but when I debug the application the container has always 'test' as the value for URL, username and password.
Here's my test class:
@ActiveProfiles("test")
@Testcontainers
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class AbstractApplicationIT {
final static DockerImageName POSTGRES_IMAGE = DockerImageName.parse("postgres:13.2-alpine");
@Container
// public static GenericContainer postgreSQLContainer = new GenericContainer(POSTGRES_IMAGE)
public static PostgreSQLContainer<?> postgreSQLContainer = new PostgreSQLContainer<>(POSTGRES_IMAGE)
// .withInitScript("tc_initscript_postgresql.sql")
// .withPassword("password")
// .withUsername("username")
// .withDatabaseName("test")
// .withInitScript("tc_initscript_postgresql.sql")
;
// @DynamicPropertySource
// static void postgresqlProperties(DynamicPropertyRegistry registry) {
// registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl);
// registry.add("spring.datasource.password", postgreSQLContainer::getPassword);
// registry.add("spring.datasource.username", postgreSQLContainer::getUsername);
// }
@Test
public void contextLoads() {
System.out.println(postgreSQLContainer.getDatabaseName());
System.out.println(postgreSQLContainer.getUsername());
System.out.println(postgreSQLContainer.getPassword());
}
}
The System.out:
test
test
test
...even without using @DynamicPropertySource
.
The container don't know the application.properties.
application.properties is Spring Boot configuration and have nothing to do with Testcontainers.
You can override values like this
@Container
private PostgreSQLContainer postgresqlContainer = new PostgreSQLContainer()
.withDatabaseName("foo")
.withUsername("foo")
.withPassword("secret");
You can also read the values from the application.properties like this:
@Value("spring.datasource.username")
private String username;