1

In a Spring Boot (2.1.3) project, I try to run an integration test against a memory H2 database (2.1.210). I also insert some data in Spring's data.sql.

I annotated the tests with @AutoConfigureTestDatabase and all worked as expected. Now I wanted to change the compatibility mode, and I find no option for doing that.

How can I customize the H2 database if I want AutoConfigureTestDatabase to create a new database for each test?

So far, I tried:

spring.test.database.replace=none
spring.datasource.url=jdbc:h2:mem;DB_CLOSE_DELAY=1;

But I ran into 'table already exists' or 'Unique constraing violation' because it seems the system does not remove the database, instead it re-executes the script on top of the existing one. The problem is described here: https://stackoverflow.com/a/47897350/3429660

I also tried to not use AutoConfigureTestDatabase, but I ran into the same problem.

user3429660
  • 2,420
  • 4
  • 25
  • 41

1 Answers1

0

I was facing same problem but found solution for that. If you look into org.springframework.boot.jdbc.EmbeddedDatabaseConnection#H2 enum value you can find the datasource url looks a little bit different

jdbc:h2:mem:%s;DB_CLOSE_DELAY=1;

When tests are instantiated there is some logic executed which replace '%s' placeholder with some UUID value. Because of that every test is executed on separate database. To implement same logic on your side you can create new Bean which do the same logic.

@Bean
public DataSource dataSource(
    @Value("${spring.datasource.driver-class-name}") String driverClassName,
    @Value("${spring.datasource.url}") String url,
    @Value("${spring.datasource.username}") String username,
    @Value("${spring.datasource.password}") String password) {
  DriverManagerDataSource dataSource = new DriverManagerDataSource();
  dataSource.setDriverClassName(driverClassName);
  dataSource.setUrl(String.format(url, UUID.randomUUID()));
  dataSource.setUsername(username);
  dataSource.setPassword(password);

  return dataSource;
}

Unfortunately you have to define all above properties in your test properties file.

frydzio
  • 1
  • 2