Performance: Test containers for database testing
This affects the test execution speed and resource usage during database integration tests.
Use Testcontainers to start a fresh database container per test or test suite.Use an embedded or shared database instance for all tests without container isolation.
| Pattern | Test Startup Time | Resource Usage | Test Reliability | Verdict |
|---|---|---|---|---|
| Shared embedded DB | Fast (milliseconds) | Low | Low (flaky tests) | [X] Bad |
| Testcontainers per test | Slower (seconds) | Medium-High | High (isolated, stable) | [OK] Good |
| Testcontainers reused | Moderate (seconds) | Medium | High | [!] OK |
Testcontainers in Spring Boot database testing?start().start(). Others use wrong method names or miss generics.start() with generic type for Testcontainers [OK]start() method and generic type for containers [OK] @Testcontainers
class MyRepositoryTest {
@Container
static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:13").withDatabaseName("testdb").withUsername("user").withPassword("pass");
@Autowired
MyRepository repo;
@Test
void testCount() {
long count = repo.count();
System.out.println(count);
}
}System.out.println(count); print if the database is empty?count() method returns the number of records in the repository's table.count() returns 0, not null or exception.org.testcontainers.containers.ContainerLaunchException. What is the likely cause? @Container
static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:latest");
@Test
void testDb() {
// test code
}Pass the test and this pattern moves unknown