Closed magnus-larsson closed 1 year ago
You have annotated your base class with @Testcontainers
, which is not the case in the Testcontainers documentation.
When you define your base class like this:
public abstract class MySqlTestBase {
// Extend startup timeout since a MySQLContainer with MySQL 8 starts very slow on Win10/WSL2
static final JdbcDatabaseContainer database;
static {
database = new MySQLContainer("mysql:8.0.32").withStartupTimeoutSeconds(300);
database.start();
}
@DynamicPropertySource
static void databaseProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", database::getJdbcUrl);
registry.add("spring.datasource.username", database::getUsername);
registry.add("spring.datasource.password", database::getPassword);
}
}
only one container is created and is reused for all tests.
Btw, this works with @ServiceConnection
, too:
public abstract class MySqlTestBase {
// Extend startup timeout since a MySQLContainer with MySQL 8 starts very slow on Win10/WSL2
@ServiceConnection
static final JdbcDatabaseContainer database;
static {
database = new MySQLContainer("mysql:8.0.32").withStartupTimeoutSeconds(300);
database.start();
}
}
Thanks for pointing it out!
When I applied the singleton pattern, I forgot to remove the @Testcontainers
annotation a long time ago.
Hasn't been a problem until now :-)
Your suggestion works like a charm!
Thanks for letting us know!
I have put together a minimal example that demonstrates how the use of
@Container
with Spring Boot 3.1.2 breaks testcontainers singleton pattern described here: https://java.testcontainers.org/test_framework_integration/manual_lifecycle_control/#singleton-containers.The example contains two test classes that share a common base class that configure a singleton test container for MySQL. When running tests, it is expected that only one MySQL test container is created.
To reproduce the problem, run the following commands:
Expect the following output demonstrating that two MySQL test containers (incorrectly) were created:
Edit
src/test/java/se/magnus/microservices/core/review/MySqlTestBase.java
and comment out the@Container
annotation.Rerunning the tests demonstrates that only one MySQL test container was created:
Expected output: