A container supplies a database endpoint; the application still needs a deterministic migration owner before repository tests run.
Spring Boot Testcontainers and Flyway: let one owner prepare the test schema
Connection is not schema
@ServiceConnection can give a test ApplicationContext the container's database connection details. It does not prove that the target schema exists or that Flyway migrations succeeded. When Spring Boot owns Flyway startup, it should apply the same versioned migrations that production uses before repository beans exercise the database. A test that creates tables manually can hide an incompatible production migration. Migration ownership matters as much as container startup.
Fail on history drift
Run a clean database through all migrations and assert the expected schema. Then run an upgrade from a retained prior schema to catch changes that only fail during rollout. Flyway checksums should not be repaired automatically to make a red test green; history integrity must remain visible. If a test fixture needs data, insert it after migrations through a named helper, not through a second schema creator.
Observe two failure types
Break a migration and assert context startup fails before the first repository call. Separately, keep migrations valid but make a repository query incompatible with a column type; assert the query fails. The container snippet from service connections remains unchanged; the verification concerns who owns the schema.
Implementation sketch
@SpringBootTest
@Import(InventoryDatabaseTestConfig.class)
class InventoryRepositoryMigrationTest {
@Autowired JdbcTemplate database;
@Test void migrationsAppliedBeforeRepositoryStarts() {
Integer completed = database.queryForObject(
"SELECT COUNT(*) FROM flyway_schema_history WHERE success = true",
Integer.class);
assertNotNull(completed);
assertTrue(completed > 0);
}
}Cost and verification
A real database and migrations increase test startup time, but they exercise SQL syntax, constraints and schema history that an in-memory substitute may miss.
Common Mistakes
- Do not assume a running container means migrations passed.
- Do not repair a checksum in tests to hide an edited applied migration.
- Do not mix Flyway ownership with a second automatic schema creator without a clear order.
Read next
Spring Boot Testcontainers: service connections and cached-context lifecycle, Spring Boot and Flyway: choose who runs migrations before traffic starts, Flyway validation: detect a changed applied migration before another write, Spring Boot migration tests: distinguish a test starter from a runtime rollout.
