I have a Spring Boot 3.1.0 project. I have application-test.properties file in src/test/resources with data source configured as below:
# application-test.properties
spring.datasource.url=jdbc:h2:mem:test;CASE_INSENSITIVE_IDENTIFIERS=TRUE;DATABASE_TO_LOWER=TRUE;DEFAULT_NULL_ORDERING=HIGH;MODE=PostgreSQL;INIT=CREATE DOMAIN IF NOT EXISTS JSONB AS JSON;
# ^^^^^^^^^^^^^^^^^
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
#spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.globally_quoted_identifiers=false
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.liquibase.enabled=false
and my test class is:
@DataJpaTest
@ActiveProfiles("test")
class UserJpaRepositoryTest {
// ...
}
When I run the test, instead of running H2 with the configuration in application-test.properties, it loads a H2 database in DEFAULT mode:
The following 1 profile is active: "test"
Bootstrapping Spring Data JPA repositories in DEFAULT mode.
Finished Spring Data repository scanning in 97 ms. Found 4 JPA repository interfaces.
Replacing 'dataSource' DataSource bean with embedded version
Starting embedded database: url='jdbc:h2:mem:46be9e88-3cd6-441f-b9fb-1dd92283945f;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
As you see here, it completely ignores spring.datasource.url and the configuration I added to databse url is not working and then my tests fail.
What I tried so far without any success:
- Rename
application-test.propertiestoapplication.properties - Move
application-test.propertiestosrc/main/resources
>Solution :
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
By default, the @DataJpaTest annotation replaces the declared db config and will configure an in-memory embedded database instance with an auto generated unique name. When you want to run tests on real database, use the @AutoConfigureTestDatabase as follows:
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class UserJpaRepositoryTest {
// ...
}