6
votes

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)

This is my test class:

@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.

3

3 Answers

8
votes

You need to tell Spring not to replace the random embedded database name with the following:

@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)

It should then pick up properties you declared in application.properties.

Please feel free to commend whether or not it works for you.

4
votes

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.

2
votes

This is something that works for me

@RunWith(SpringRunner.class)
@TestPropertySource(locations = "classpath:application-mysql.properties")
@SpringBootTest
public abstract class ExternalDbApplicationTestBase {

}

I use this class as a base for all related db integration classes.