Sub topic 12
Testing migrations against a real database
This chapter assumes you can write versioned migrations (V1__...sql), you know how Spring Boot runs Flyway at startup, and you have written a basic JUnit 5 test. Docker must be available on the machine that runs the tests.
Why test migrations at all
A migration is code that runs once, against data you cannot easily recreate. If it fails in production, Flyway stops the application at startup. The cheapest place to find a syntax error, a missing column, or a constraint that existing rows violate is a test that runs on every build.
Migration tests answer three questions:
- Does every migration apply cleanly to an empty database?
- Does the resulting schema match what the JPA entities expect?
- Does a migration that changes existing data produce the right result?
Why not H2
Many projects test with an in-memory H2 database because it needs no setup. For migrations this is a poor choice. Your production migrations are written in PostgreSQL SQL, and H2's compatibility modes only approximate it. Differences show up in identity columns, CREATE OR REPLACE VIEW, type names, partial indexes, and procedural code. A migration can pass on H2 and fail on PostgreSQL, or the reverse. The second case is worse, because it makes you rewrite correct SQL to please the test database.
Run the tests against the same database engine, and the same major version, that you run in production. Testcontainers does this by starting a throwaway PostgreSQL container for the test run.
Adding Testcontainers
Add these test-scoped dependencies. Spring Boot's dependency management supplies the versions.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>The class and package names below are the Testcontainers 1.x ones, which Spring Boot 3 manages. Testcontainers 2.x renamed some artifacts and packages, so check the names your Boot version manages.
A full-startup test
The simplest migration test starts the whole application context. Spring Boot runs Flyway during startup, so a broken migration makes the context fail to load, and the test fails with Flyway's error message.
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.testcontainers.service.connection.ServiceConnection;
import org.springframework.jdbc.core.JdbcTemplate;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
@Testcontainers
class MigrationsTest {
@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@Autowired
Flyway flyway;
@Autowired
JdbcTemplate jdbc;
@Test
void allMigrationsAreApplied() {
assertEquals(0, flyway.info().pending().length);
}
@Test
void noMigrationFailed() {
Integer failed = jdbc.queryForObject(
"SELECT count(*) FROM flyway_schema_history WHERE success = false",
Integer.class);
assertEquals(0, failed);
}
@Test
void repeatableViewIsQueryable() {
Integer rows = jdbc.queryForObject("SELECT count(*) FROM active_users", Integer.class);
assertEquals(0, rows);
}
}@ServiceConnection tells Spring Boot to take the JDBC URL, user, and password from the container. You do not set spring.datasource.* in the test. Flyway and Hibernate both use that connection.
The test in the last method queries the active_users view from the repeatable migration. A view that references a missing column often fails only when it is created, but querying it also proves that it exists.
Schema validation as a free test
If you set spring.jpa.hibernate.ddl-auto: validate, the same test also checks that every entity maps to an existing table and column with a compatible type. A migration that forgets a column, or an entity that renames a field without a migration, makes the context fail. This catches drift between code and schema without any extra assertions.
Testing a data migration
Starting from an empty database does not exercise migrations that change existing rows. The V3__Backfill_display_name migration updates rows that already exist, but on an empty database it updates nothing, so a bug in it would go unnoticed.
To test it, migrate to the previous version, insert data in the old shape, then migrate the rest of the way. Flyway's target setting stops the migration at a given version. This test uses the Flyway API directly and needs no Spring context.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Testcontainers
class BackfillMigrationTest {
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
@Test
void backfillCopiesUsernameIntoDisplayName() throws Exception {
Flyway.configure()
.dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())
.target("2")
.load()
.migrate();
try (Connection c = DriverManager.getConnection(
postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword());
Statement st = c.createStatement()) {
st.execute("INSERT INTO app_user (username) VALUES ('alice')");
Flyway.configure()
.dataSource(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword())
.load()
.migrate();
try (ResultSet rs = st.executeQuery(
"SELECT display_name FROM app_user WHERE username = 'alice'")) {
assertTrue(rs.next());
assertEquals("alice", rs.getString("display_name"));
}
}
}
}The first migrate() applies V1 and V2. The insert creates a row with a null display_name, as production rows would have at that point. The second migrate() has no target, so it applies V3 and everything after it. Seed data that resembles production, including awkward values such as nulls, duplicates, and very long strings.
This test relies on the default location, classpath:db/migration. That location also finds Java migrations in the db.migration package.
Common mistakes
- Replacing the datasource in slice tests.
@DataJpaTestswaps your datasource for an embedded database by default. Flyway then runs against H2 instead of the container. Add@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)so the container is used. - Disabling Flyway in the test profile. A test
application.ymlthat setsspring.flyway.enabled: falseandddl-auto: create-droptests Hibernate's schema, not yours. Keep the test configuration the same as production for these properties. - Sharing state between tests. A static container lives for the whole class, and its data persists between test methods. Clean up rows you insert, or use a fresh container for tests that depend on an empty schema.
- Using
cleanto reset. Recent Flyway versions disablecleanby default, because it drops every object in the schema. Do not enable it outside tests. A fresh container does not need it. - Testing only the newest migration. The full-startup test applies every migration from
V1. That is the point: it proves a new developer or a CI server can build the schema from nothing.
What to run in CI
Run migration tests on every pull request. They need Docker, so check that your CI runners provide it. A failing migration test blocks the merge, which stops a broken file from reaching the main branch, where it would break every developer's local database.
Exercise
Your V5 migration changes a column from VARCHAR(50) to INTEGER and converts existing values with a USING clause. The full-startup test passes. Why is that not enough, and what test would you add?
Show answer
The full-startup test runs V5 against an empty database, so no rows are converted and a bad USING expression is never exercised. Add a test that migrates to version 4 with target("4"), inserts rows in the old shape (including values that are not valid numbers, if your data allows them), migrates the rest of the way, and asserts that the converted values are correct or that the migration fails as expected.