Running Flyway migrations in tests
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Production builds ShopLite's tables with Flyway scripts, but a test container starts empty. How do the tests get the same tables, and how do they notice a broken migration before a deploy does?
Flyway builds the test schema from the production scripts
A Flyway migration is a versioned SQL file such as V2__add_index.sql. Flyway runs the files in version order, once each, and records every one in the flyway_schema_history table.
A new MySQL container is empty. Flyway fills it from the same V1, V2, ... scripts production runs, and this model shows the order it uses.
Example 1 · How Flyway orders versions
import java.util.ArrayList;import java.util.Arrays;import java.util.Comparator;import java.util.List;
public class MigrationOrderDemo { // "V1_2__test_customers.sql" -> [1, 2] static int[] version(String file) { String v = file.substring(1, file.indexOf("__")); return Arrays.stream(v.split("_")).mapToInt(Integer::parseInt).toArray(); }
static final Comparator<String> BY_VERSION = (a, b) -> Arrays.compare(version(a), version(b));
public static void main(String[] args) { List<String> files = new ArrayList<>(List.of( "V10__add_coupons.sql", "V2__add_order_history_index.sql", "V1__create_schema.sql", "V1_2__test_customers.sql", "V3__add_product_description.sql"));
List<String> asText = new ArrayList<>(files); asText.sort(Comparator.naturalOrder()); System.out.println("Sorted as text : " + asText);
files.sort(BY_VERSION); System.out.println("Flyway's order : " + files); }}Sorted as text : [V10__add_coupons.sql, V1_2__test_customers.sql, V1__create_schema.sql, V2__add_order_history_index.sql, V3__add_product_description.sql] Flyway's order : [V1__create_schema.sql, V1_2__test_customers.sql, V2__add_order_history_index.sql, V3__add_product_description.sql, V10__add_coupons.sql]
What this code does
- Flyway compares versions as numbers part by part, so
1<1.2<2<3<10, no matter which folder a file is in. A text sort would putV10first and run it before the table exists. - The test-only
V1_2__test_customers.sqllands right afterV1because of its version number; the main folder anddb/testdataare merged into one ordered list.
Spring Boot runs Flyway when the application context starts, test contexts included. The database is new on every run, so Flyway applies all migrations from V1: there is no separate test schema, no schema.sql and no H2-friendly copy. If the scripts work here, they work on any empty MySQL 8.4.
Predict the output
Which file runs first?
Flyway orders versions as numbers, part by part. Pick the file that runs first.
Round 1 of 2
Two files in the migration folder.
ddl-auto=validate catches entity and schema mismatches
ddl-auto=validate is a Hibernate setting (spring.jpa.hibernate.ddl-auto) that compares every entity with the real tables at start-up and refuses to start when they disagree: a missing column, a missing table or a wrong type.
ShopLite already uses validate in production, so keep it in tests. Change an entity without its migration and the context fails at once, as here.
Example 2 · validate stops the context: the entity says FLOAT, the table says DECIMAL
Runs in: the shoplite-api Spring Boot project with Docker running
// Product.java after a careless change (money must be BigDecimal)@Column(nullable = false)private Double price;
// any integration test, for example@SpringBootTest@Import(MySqlTestcontainersConfig.class)class ProductApiIT { @Test void contextStarts() { }}[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 -- in com.shoplite.product.ProductApiIT [ERROR] contextStarts Time elapsed: 0.01 s <<< ERROR! java.lang.IllegalStateException: Failed to load ApplicationContext ... Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema validation: wrong column type encountered in column [price] in table [products]; found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)]
What this code does
- Flyway created
price DECIMAL(10,2), the entity now maps aDouble, and Hibernate's validation refuses to start. The message names the table, the column, what it found and what the entity expects. - Every test in the context fails with "Failed to load ApplicationContext"; scroll to the last
Caused byfor the real reason. The fix here is to change the entity back toBigDecimal.
The setting costs nothing and turns a missing migration into a failed build on your laptop instead of a failed deploy.
Fix the error
Fix the entity
Read the real error, then pick the line that fixes the entity.
Flyway made price DECIMAL(10,2). The entity was changed carelessly.
Error
Schema validation: wrong column type encountered in column [price] in table [products]; found [decimal (Types#DECIMAL)], but expecting [float(53) (Types#FLOAT)]
Test data: a test-only migration location or @Sql
spring.flyway.locations is the property that lists the folders Flyway reads migrations from. A test profile can add classpath:db/testdata, so test-only migrations run in version order with the real ones.
Some tests need rows that production must never have. Add a test-only folder to Flyway's locations in the test profile.
# src/test/resources/application-test.ymlspring: flyway: locations: classpath:db/migration,classpath:db/testdata jpa: hibernate: ddl-auto: validateExample 3 · Test data in a test-only migration and with @Sql
Runs in: the shoplite-api Spring Boot project (test resources)
-- src/test/resources/db/testdata/V1_2__test_customers.sql-- Runs only in tests (spring.flyway.locations in application-test.yml)INSERT INTO customers (full_name, email, phone) VALUES ('Test Buyer', 'buyer@test.shoplite', '9000000001'), ('Test No Address', 'no-address@test.shoplite', NULL);
INSERT INTO categories (name) VALUES ('Test Category');
-- And for one test only, in Java:-- @Test-- @Sql(statements = "UPDATE products SET stock = 0 WHERE sku = 'MOB-RN13'")-- void outOfStockProductCannotBeOrdered() { ... }INFO o.f.core.internal.command.DbMigrate -- Migrating schema `test` to version "1 - create schema" INFO o.f.core.internal.command.DbMigrate -- Migrating schema `test` to version "1.2 - test customers" INFO o.f.core.internal.command.DbMigrate -- Migrating schema `test` to version "2 - add order history index" INFO o.f.core.internal.command.DbMigrate -- Successfully applied 3 migrations to schema `test`, now at version v2
What this code does
- The test migration has its own version (1.2), so Flyway runs it once per container, in order, and records it like any other. The emails use a test-only domain, so they can never clash with real data.
- The
@Sqlline changes one product just for one test and is rolled back with that test in a@DataJpaTest; use it for data that a single test depends on.
Two ways to add test data:
- Test-only migrations: files such as
V1_2__test_customers.sqlinsrc/test/resources/db/testdatarun once per container, in version order. @Sqlper test: statements that run before one test or class;@DataJpaTestrolls them back.
Use test migrations for a small, stable base that many tests read, and @Sql for data that one test changes or depends on.
Find the bug
Find the configuration slip
Each snippet is wrong for tests. Tap the line with the mistake.
The customer buyer@test.shoplite is never found.
Round 1 of 3A test that proves the migrations apply from empty
pending() is the Flyway call flyway.info().pending() that lists migrations found in the files but not yet applied. After a start from an empty database it must be empty.
A migration test asks Flyway what it did and asserts it. It runs against an empty container, like a first deploy to a new server.
Example 4 · src/test/java/com/shoplite/MigrationsApplyFromEmptyIT.java
Runs in: the shoplite-api Spring Boot project with Docker running
package com.shoplite;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import org.flywaydb.core.Flyway;import org.flywaydb.core.api.MigrationInfo;import org.flywaydb.core.api.MigrationState;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.context.annotation.Import;
@SpringBootTest@Import(MySqlTestcontainersConfig.class)class MigrationsApplyFromEmptyIT {
@Autowired Flyway flyway;
@Test void everyMigrationAppliedAndNothingPending() { MigrationInfo[] applied = flyway.info().applied();
assertThat(applied).isNotEmpty(); assertThat(Arrays.stream(applied).map(MigrationInfo::getState)) .containsOnly(MigrationState.SUCCESS); assertThat(flyway.info().pending()).isEmpty(); assertThat(flyway.info().current().getVersion().getVersion()).isEqualTo("2"); }}[INFO] Running com.shoplite.MigrationsApplyFromEmptyIT INFO tc.mysql:8.4 -- Container is started (JDBC URL: jdbc:mysql://localhost:55061/test) INFO o.f.core.internal.command.DbValidate -- Successfully validated 2 migrations (execution time 00:00.027s) INFO o.f.core.internal.command.DbMigrate -- Current version of schema `test`: << Empty Schema >> INFO o.f.core.internal.command.DbMigrate -- Migrating schema `test` to version "1 - create schema" INFO o.f.core.internal.command.DbMigrate -- Migrating schema `test` to version "2 - add order history index" INFO o.f.core.internal.command.DbMigrate -- Successfully applied 2 migrations to schema `test`, now at version v2 (execution time 00:01.144s) [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 18.27 s -- in com.shoplite.MigrationsApplyFromEmptyIT
What this code does
<< Empty Schema >>in the log proves the run started from nothing, like a first deploy. The test then pins three facts: all applied migrations succeeded, none is pending, and the schema is at the version you expect.- Update the expected version in the same commit as each new migration; a forgotten file in the wrong folder then shows up as a failing assertion.
Spring Boot's own Flyway bean can be injected into the test. info().applied() lists the migrations in the history table, and pending() those still waiting.
Order of execution
Order the migration test
Tap the steps in the order they happen.
A migration that fails only on real MySQL
flyway_schema_history is the table in which Flyway records each migration it applied, with its version, checksum and whether it succeeded. A failed migration leaves a failed row there on a real server.
When a migration fails, Flyway stops the context with a block that names the file, the line and MySQL's own message.
Migration V3__add_product_description.sql failed------------------------------------------------SQL State : 42000Error Code : 1170Message : BLOB/TEXT column 'description' used in key specification without a key lengthLocation : db/migration/V3__add_product_description.sql (...)Line : 4Statement : CREATE INDEX idx_products_description ON products (description)Example 5 · The failing V3 and its fix
Runs in: the shoplite-api project, src/main/resources/db/migration
-- V3__add_product_description.sql: BROKEN on MySQL (worked on H2)ALTER TABLE products ADD COLUMN description TEXT NULL;
CREATE INDEX idx_products_description ON products (description);
-- V3__add_product_description.sql: FIXED (file not yet applied anywhere, so it may still change)ALTER TABLE products ADD COLUMN description TEXT NULL;
-- index only the first 100 characters; MySQL needs a prefix length for TEXTCREATE INDEX idx_products_description ON products (description(100));(broken file) Migration V3__add_product_description.sql failed Error Code : 1170 Message : BLOB/TEXT column 'description' used in key specification without a key length (fixed file, next run on a fresh container) INFO o.f.core.internal.command.DbMigrate -- Migrating schema `test` to version "3 - add product description" INFO o.f.core.internal.command.DbMigrate -- Successfully applied 3 migrations to schema `test`, now at version v3
What this code does
- MySQL cannot index a whole
TEXTvalue, so it asks for a key length;description(100)indexes the first 100 characters. For word search, aFULLTEXTindex is the other option. - Changing V3 is allowed only because it has never run on a shared database. Once a migration has run anywhere, fix it with a new V4 instead (Section 16's rule).
Read the Message first: it is MySQL's own explanation.
MySQL cannot roll back DDL statements such as CREATE INDEX or ALTER TABLE, so on a real server a half-run migration leaves partial changes, which you clean up and then flyway repair (Section 16). In a Testcontainer you fix the script and run again: the next container starts empty.
Fix the error
Fix the failing V3
Read the real MySQL error, then pick the line that fixes the migration.
V3 passed on H2 and has not run anywhere else yet.
Error
Error Code : 1170 Message : BLOB/TEXT column 'description' used in key specification without a key length
Next step
Check your understanding
12 quick questions