Video in progress

Strong Middle 🧪 Testing

How do you check in a test that Flyway migrations and JPA entities match each other?

In tests Flyway, not Hibernate, should create the schema: migrations run on a real PostgreSQL (Testcontainers), and then spring.jpa.hibernate.ddl-auto=validate makes Hibernate check that the tables and columns of the entities exist in the database. If they don't match, the context won't start and the test fails immediately.

📖 Answer

The most common mistake: ddl-auto=create-drop in tests (which is also Boot's default with an embedded database) and Flyway in prod. A developer adds a discountPercent field to the entity and forgets to write a migration. The tests are green, because Hibernate created the column itself. After the deploy, the first request fails with column "discount_percent" does not exist.

The right setup:

# src/test/resources/application-test.yml
spring:
  jpa:
    hibernate:
      ddl-auto: validate
  flyway:
    enabled: true
@SpringBootTest
@ActiveProfiles("test")
@Import(TestContainersConfig.class)   // @ServiceConnection PostgreSQL
class SchemaIT {
    @Test
    void contextStartsWithMigratedSchema() {
        // context started = migrations ran and validate found no errors
    }
}

This one "empty" test catches a lot: whether the migration syntax really works on PostgreSQL, a missing table or column, a type mismatch (integer instead of varchar).

validate has limits: it doesn't check indexes, unique constraints and, in many cases, NOT NULL. For those you need repository tests, for example saving two identical emails and checking that a DataIntegrityViolationException is thrown.

Two more things:

  • flyway.validate-on-migrate (on by default) gives a checksum error if an already-applied migration file is changed. Don't turn this off in tests;
  • you need to test migrations not only on an empty database but also on one with prod-like data: adding NOT NULL passes on an empty table and fails on a table with existing rows.