使用 H2 数据库和 Liquibase 配置 Spring Boot

jav*_*Try 7 junit h2 liquibase spring-boot

我正在使用 Spring boot2,我正在尝试使用 H2 + Liquibase + JUNIT 配置单元测试。

我认为 liquibase 没有执行 changeLog 文件并应用 SQL 命令,单元测试无法识别我的表。

我将错误的 sql 放在我的文件中以查看是否执行了更改日志文件,但是,似乎没有执行。

为什么我的应用程序无法访问表?也许 liquibase 没有执行?

在我的src/test/resource我有这个文件:application.yml

spring:
  application:
    name: my-api
  datasource:
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:myDB;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: sa
    password: sags
  liquibase:
    enabled: true
    user: sa
    password: sags
    change-log: classpath:/db/changelog/db.changelog-master.xml
  jpa:
    hibernate:
      ddl-auto: none
      database-platform: org.hibernate.dialect.H2Dialect
    show-sql: true
    properties:
      hibernate:
        use_sql_comments: true
        format_sql: true
  h2:
    console:
      enabled: true
      path: /console
Run Code Online (Sandbox Code Playgroud)

我的测试课:

import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class FooRepositoryTest {

    @Autowired
    private FooRepository fooRepository;

    @Test
    public void findAllMustReturnAnything() {
        List<Object> result = fooRepository.tables();
    }
}
Run Code Online (Sandbox Code Playgroud)

FooRepository 方法:

@Query(value = "SHOW TABLES", nativeQuery = true)
    List<Object> tables();
Run Code Online (Sandbox Code Playgroud)

当我运行我的单元测试时,我有以下结果:

在此处输入图片说明

我的变更日志文件在:src/main/resources/db

更新:我找到了为什么 liquibase 没有执行我的 sql 代码。这是因为我的 SQL 文件有“dbms:mysql”,所以,我如何使用 H2 liquibase 执行将不适用。

-- changeset 1.0:2 dbms:mysql
command
-- rollback command
Run Code Online (Sandbox Code Playgroud)

现在,我需要知道为什么我在会话中选择的数据库不是 myDB。

小智 2

我认为在你的情况下Spring打开自动配置数据源。(https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/api/org/springframework/boot/test/autoconfigure/orm/jpa /AutoConfigureTestDatabase.Replace.html

尝试将其关闭。

spring.test.database.replace=none
Run Code Online (Sandbox Code Playgroud)

还有一些不必要的配置。

  liquibase:
    user: sa
    password: sags
Run Code Online (Sandbox Code Playgroud)

您可以删除用户和密码,liquibase 从数据源中使用它。