Issue
I am trying to create a test that uses an embedded H2 database. But I have to change the spring.datasource.url, I cannot use the default one that is created by spring boot. (this is because I have to change the mode of the H2 database to MYSQL)
@JdbcTest
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class DemoApplicationTests {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
DataSource dataSource;
@Test
public void contextLoads() {
System.out.println(dataSource);
}
}
This is my application-test.properties
:
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MYSQL
spring.datasource.username=dbuser
spring.datasource.password=dbpass
My dependencies:
compile('org.springframework.boot:spring-boot-starter-batch')
runtime('com.h2database:h2')
compile group: 'org.springframework.boot', name: 'spring-boot-starter-jdbc', version: '1.5.3.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.5.3.RELEASE'
The console output:
Starting embedded database: url='jdbc:h2:mem:bfad6b71-3e2d-4a47-a32d-c76988b3c5f6;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false', username='sa'
I would expect the url to be something like this: jdbc:h2:mem:testdb
, I also want it to pick up the MODE=MYSQL
setting.
I tried to follow this post, but it didn't work.
Solution
Spring Boot's @DataJdbcTest
, @DataJpaTest
and @JdbcTest
, through @AutoConfigureTestDatabase
will all end up calling TestDatabaseAutoConfiguration
, which in turn, by default, will configure an in-memory embedded database instance with an auto generated unique name.
That may give you problems if, e.g. you happen to use an JPA Entity with a @Table
with a non-blank catalog
attribute, as H2 requires that catalog name to be the same as its database name.
As Dane Savot said in his answer
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
will solve the problem for that test class, but if you want to solve it globally, add
spring.test.database.replace=none
to your src/test/resources/application.properties
or .yaml
. That property controls @AutoConfigureTestDatabase.replace
's behavior.
Answered By - Bruno Laturner
Answer Checked By - David Marino (JavaFixing Volunteer)