简体   繁体   中英

Configure Spring boot with H2 database and Liquibase

I am using Spring boot2, I am trying to configure a Unit Test using H2 + Liquibase + JUNIT.

I think that liquibase is not executing the changeLog files and apply the SQL Commands, the unit test does not recognized my tables.

I put wrongs sql in my file to see if the changelog files are executed, but, seems that is not being executing.

Why my application can not access table? Maybe liquibase is not executing?

in my src/test/resource I have this file: 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

My Test class:

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();
    }
}

The FooRepository method:

@Query(value = "SHOW TABLES", nativeQuery = true)
    List<Object> tables();

When I run my Unit Test I have the follow result:

在此处输入图像描述

My changelog file is in : src/main/resources/db

UPDATE: I found why liquibase was not executing my sql codes. It was because my SQL files had "dbms:mysql", so, how I am executing with H2 liquibase will not apply.

-- changeset 1.0:2 dbms:mysql
command
-- rollback command

Now, I need to know why my selected database in the session is not myDB.

I think in you case Spring turns on auto configure datasource.( https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/api/org/springframework/boot/test/autoconfigure/orm/jpa/AutoConfigureTestDatabase.Replace.html )

Try to turn it off.

spring.test.database.replace=none

And there is some unnecessary configuration.

  liquibase:
    user: sa
    password: sags

You can remove user&password, liquibase use it from datasource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM