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
We can define schema by creating a SQL file in the resource folder (src/main/resource). We can populate data in the table by creating a SQL file in the resource folder (src/main/resource). Spring Boot automatically picks up the data. sql file and run it against the H2 database during the application startup.
@DataJpaTest is used to test JPA repositories. It is used in combination with @RunWith(SpringRunner. class) . The annotation disables full auto-configuration and applies only configuration relevant to JPA tests.
You can create a @DataJpaTest and @Autowire your repository into it. For example: @RunWith(SpringRunner. class) @DataJpaTest public class MyJpaTest { @Autowired private ChartRepository chartRepository; @Test public void myTest() { ... } }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With