SpringBoot - Testing with Flyway and H2 database

AleGallagher picture AleGallagher · Aug 28, 2018 · Viewed 17.3k times · Source

I'm coding acceptance tests with Cucumber, and I want to use a H2 database for the tests.

The application-test.properties looks like:

server.port:8090

spring.jpa.database=H2
spring.database.driverClassName=org.h2.Driver
spring.datasource.url:jdbc:h2:mem:database_user;DB_CLOSE_ON_EXIT=FALSE
flyway.locations=classpath:resources/db/migration
flyway.enabled=true

spring.datasource.username:SA
spring.datasource.password:

spring.h2.console.enabled=true
spring.jpa.show-sql=true

security.basic.enabled:false
spring.application.name=userService

In the directory resources/db/migration, I have a sql file with these scripts:

create table user_image(
 id int unsigned not null AUTO_INCREMENT,
 url varchar(1000) not null,
 s3_key varchar(200) not null,
 PRIMARY KEY (id)
);


create table user (
    id int unsigned not null AUTO_INCREMENT,
    email varchar(50) not null,
    password varchar(100) not null,
    first_name varchar(50) not null,
    last_name varchar(50) not null,
    description varchar(50),
    phone_number varchar(50),
    user_image_id int unsigned,
    need_refresh_pass boolean not null,
    PRIMARY KEY (id),
    CONSTRAINT fk_user_image FOREIGN KEY (user_image_id)
    REFERENCES user_image(id)
);

But when I run the tests, H2 creates the schema with default format instead of using the scripts:

enter image description here

As you can see, all the VARCHAR are created with 255 size, instead of the real value.

Could you help me to integrate flyway with H2?

Thanks!

Answer

gmolaire picture gmolaire · Aug 28, 2018

1- Make sure that your hibernate DDL generation is disabled:

spring.jpa.hibernate.ddl-auto=none

2- Make sure that the name of your SQL migration script respects flyway's convention. i.e.

V1__create_user_table_for_test.sql