Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Test seems to be creating H2 Test DB different than what I would expect

So, I have a Test annotated with @DataJpaTest and @RunWith(SpringRunner.class), and an application.yml under /src/test/resources with this block (yes, indenting should be fine):

spring:
  datasource:
    url: jdbc:h2:mem:foobar;MODE=Mysql;MVCC=FALSE;
    username: sa
    password:
    driver-class-name: org.h2.Driver

When I start the Test, I unexpectedly get these lines in the log:

2019-10-23 17:11:08.311  INFO 13468 --- [           main] beddedDataSourceBeanFactoryPostProcessor : Replacing 'dataSource' DataSource bean with embedded version
2019-10-23 17:11:08.801  INFO 13468 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:h2:mem:7855270f-61b7-4f37-8796-cbfeb8ad42ea;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'

In particular this: Starting embedded database: url='jdbc:h2:mem:7855270f-61b7-4f37-8796-cbfeb8ad42ea;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false

Why is Spring boot starting a DB with a UUID-Generated DB and not taking the settings from spring.datasource.url?

The "productive" app takes the datasource settings fine from the file in /src/main/resources with same syntax without issues...

like image 922
Martin Avatar asked Sep 17 '25 13:09

Martin


1 Answers

From the documentation of @DataJpaTest you can see that:

@DataJpaTest uses an embedded in-memory database (replacing any explicit or usually auto-configured DataSource). The @AutoConfigureTestDatabase annotation can be used to override these settings.

So @DataJpaTest annotated with @AutoConfigureTestDatabase that causes TestDatabaseAutoConfiguration to create embedded datasource with hard-coded generateUniqueName(true):

TestDatabaseAutoConfiguration.java :

EmbeddedDatabase getEmbeddedDatabase() {
    ...
    return new EmbeddedDatabaseBuilder()
        .generateUniqueName(true)
        .setType(connection.getType())
        .build();
}

I think they do this to prevent DB name collisions and state mix between test runs.

like image 185
i.bondarenko Avatar answered Sep 21 '25 09:09

i.bondarenko