使用@DataJpaTest设置自定义方案

Nin*_*ina 7 java junit h2 jpa-2.1 spring-boot

我想用Spring Boot测试一个Repository,并希望包含TestEntityManager来检查存储库是否真的应该做它应该做的事情.

这是JUnit测试:

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

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private MyRepository repository;

    ...
Run Code Online (Sandbox Code Playgroud)

对于其他JUnit测试,我有一个application-junit.properties文件,用于设置包含一些表,索引,序列和约束的模式:

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
Run Code Online (Sandbox Code Playgroud)

现在,使用DataJpaTest似乎没有使用此配置.即使我添加@ActiveProfiles("junit").

如何使JUnit测试使用我的create.h2.sql文件来设置表?

提前谢谢,妮娜

Ste*_*oll 16

这不是因为内存数据源@DataJpaTest替换了您配置的数据源.

如果您不希望这样,那么junit特殊配置文件就是这种情况,您需要指示Spring Boot不要覆盖您的配置DataSource.我在上面给出的链接中有一个示例.基本上,您的测试应如下所示:

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

你应该考虑创建一个元注释来分享最后两个(三个?)注释,这样你就不必一遍又一遍地重复这个注释.