Setting up custom scheme using @DataJpaTest

Nina picture Nina · Dec 27, 2016 · Viewed 9k times · Source

I want to test a Repository with Spring Boot and want to include TestEntityManager to check that the repository really does what it should do.

That's the JUnit Test:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private MyRepository repository;

    ...

For the other JUnit tests I have an application-junit.properties file that sets up a schema with some tables, indexes, sequences and constraints:

spring.datasource.url=jdbc:h2:mem:testdb;Mode=Oracle;INIT=create schema if not exists testdb\\;SET SCHEMA testdb\\;runscript from 'classpath:create.h2.sql';
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.platform=h2
spring.jpa.hibernate.ddl-auto=none
spring.datasource.continue-on-error=true

#datasource config
spring.database.driver-class-name=org.h2.Driver
spring.database.jndi-name=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true

Now, with DataJpaTest this configuration does not seem to be used. Even if I add @ActiveProfiles("junit").

How can I make the JUnit test use my create.h2.sql file to set up the tables?

Thanks in advance, Nina

Answer

Stephane Nicoll picture Stephane Nicoll · Dec 27, 2016

It isn't because @DataJpaTest replaces your configured datasource by an in-memory data source.

If you don't want that, which is clearly the case with that junit special profile, you need to instruct Spring Boot not to override your configureed DataSource. There is an example in the doc in the link I gave above. Essentially, your test should look like this:

@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("junit")
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class MyRepositoryTest {
   ...
}

You should consider creating a meta-annotation to share the last two (three?) annotations so that you don't have to repeat this over and over again.