SpringBoot - 使用Flyway和H2数据库进行测试

5
我是一个使用Cucumber编写验收测试的开发者,我想在测试中使用H2数据库。
应用程序测试属性文件如下:
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

在资源/db/migration目录中,我有一个包含以下脚本的sql文件:
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)
);

但是当我运行测试时,H2会使用默认格式创建模式,而不是使用脚本:

enter image description here

正如您所看到的,所有的VARCHAR都是用255的大小创建的,而不是实际值。

您能帮我将flyway与H2集成吗?

谢谢!

3个回答

2

1- 确保你的Hibernate DDL生成已禁用:

spring.jpa.hibernate.ddl-auto=none

2- 确保您的SQL迁移脚本名称符合Flyway的约定,即:

V1__create_user_table_for_test.sql

1
Flyway没有找到任何迁移,因此Hibernate从您的实体创建了表。
位置应该是:
# spring-boot 2.x
spring.flyway.locations=classpath:db/migration

# spring-boot 1.5.x
flyway.locations=classpath:db/migration

这是默认值,可以省略。

0
我发现为数据源定义一个固定的dataSource可以解决这个问题:
在/test下创建一个类。
package com.whatever;

import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.SimpleDriverDataSource;

import javax.sql.DataSource;

public class TestDataSource {
    @Bean
    public DataSource dataSource() {
        SimpleDriverDataSource dataSource = new SimpleDriverDataSource();
        dataSource.setDriverClass(org.h2.Driver.class);
        dataSource.setUrl("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE;DATABASE_TO_UPPER=false;MODE=MYSQL");
        dataSource.setUsername("sa");
        return dataSource;
    }
}

在你的测试中使用配置。例如:

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestDataSource.class})
@SpringBootTest(classes = Application.class)
@AutoConfigureMockMvc
@ActiveProfiles({ "test" })
@TestExecutionListeners({DbUnitTestExecutionListener.class, DependencyInjectionTestExecutionListener.class})
public class SomethingControllerTest {
...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接