Currently, I want to create an integration test for my system. I'm using testcontainers to spawn my temporary database instance, and use R2DBC Database to make my system reactive. The problem is I don't know how to create a schema in R2DBC testcontainer instance, there's clear difference in the documentation between R2DBC support and JDBC support in testcontainers web page. In JDBC, there're section to create schema after we replace JDBC URL, meanwhile in R2DBC there isn't any mention about schema creation after we replace R2DBC URL. I've tried and explored the method in PostgreSQLR2DBCDatabaseContainer
, but it didn't work.
I'm also use spring boot for our system's framework, and usually I replace the URL using ContextConfiguration
initializer. Is there any way to create a schema after I replace the URL for R2DBC?
You have the following options to achieve what you want:
If you're using Spring Boot, here an article showing its use with the singleton pattern: https://rieckpil.de/reuse-containers-with-testcontainers-for-fast-integration-tests/.
For the singleton container approach you should do something similar to this:
public abstract class PostgresTestContainer {
private final PostgreSQLContainer<?> postgresContainer =
new PostgreSQLContainer<>("postgres:13.3-alpine")
.withDatabaseName("foo")
.withUsername("foo")
.withPassword("secret");
static {
postgresContainer.start();
}
@DynamicPropertySource
private static void setDatasourceProperties(DynamicPropertyRegistry registry) {
// JDBC DataSource Example
registry.add("spring.datasource.url", postgresContainer::getJdbcUrl);
registry.add("spring.datasource.password", postgresContainer::getPassword);
registry.add("spring.datasource.username", postgresContainer::getUsername);
// R2DBC DataSource Example
registry.add("spring.r2dbc.url", () ->
format("r2dbc:pool:postgresql://%s:%d/%s",
postgresContainer.getHost(),
postgresContainer.getFirstMappedPort(),
postgresContainer.getDatabaseName()));
registry.add("spring.r2dbc.username", postgresContainer::getUsername);
registry.add("spring.r2dbc.password", postgresContainer::getPassword);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With