For your case, you should create properties to a R2dbc connection instead of the Jdbc connection.
You have to compute the R2dbc URL manually instead of the Jdbc URL.
registry.add("spring.r2dbc.url", () -> "r2dbc:postgresql://"
+ postgreSQLContainer.getHost() + ":" + postgreSQLContainer.getFirstMappedPort()
+ "/" + postgreSQLContainer.getDatabaseName());
registry.add("spring.r2dbc.username", () -> postgreSQLContainer.getUsername());
registry.add("spring.r2dbc.password", () -> postgreSQLContainer.getPassword());
More simply you can create a tc
profile based application config for testcontainers.
# src/test/resources/application-tc.properties
spring.r2dbc.url=r2dbc:tc:mysql:///databasename?TC_IMAGE_TAG=8
The tc
in the url will start a testcontaienrs docker automatically. See the TestContainers R2dbc support.
Then you can also apply some some initial work(eg. create schemas and insert sample data) via a @TestConfiguration
.
@DataR2dbcTest
@TestInstance(TestInstance.Lifecycle.PER_METHOD)
@ActiveProfiles("tc")// activate the `tc` profile.
public class TestcontainersPostRepositoryTest {
@TestConfiguration
static class TestConfig {
@Bean
public ConnectionFactoryInitializer initializer(ConnectionFactory connectionFactory) {
ConnectionFactoryInitializer initializer = new ConnectionFactoryInitializer();
initializer.setConnectionFactory(connectionFactory);
CompositeDatabasePopulator populator = new CompositeDatabasePopulator();
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("schema.sql")));
populator.addPopulators(new ResourceDatabasePopulator(new ClassPathResource("data.sql")));
initializer.setDatabasePopulator(populator);
return initializer;
}
}
@Autowired
DatabaseClient client;
@Autowired
PostRepository posts;
//your tests...
I have some testcontainers examples.
Launch Contrainer via R2dbc url, see this R2dbc MySQL example.
Manual setup with Junit, see this R2dbc PostgresSQL example.
Use spring initializer classes to initialize a Container, see this Neo4j Rx example.