2016-12-27 79 views
3

我想用Spring Boot测试一个存储库,并且想要包含TestEntityManager来检查存储库是否确实应该做什么。使用@DataJpaTest设置自定义方案

这是JUnit测试:

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

    @Autowired 
    private TestEntityManager entityManager; 

    @Autowired 
    private MyRepository repository; 

    ... 

对于其他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 

现在,用DataJpaTest这个配置似乎没有被使用。即使我添加@ActiveProfiles(“junit”)。

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

由于提前, 尼娜

回答

5

这并不是因为@DataJpaTest取代your configured datasource by an in-memory data source

如果你不想要那个,那明显是junit特殊配置文件的情况,你需要指示Spring Boot不要覆盖配置的DataSource。在我上面给出的链接中的文档中有一个例子。从本质上讲,你的测试应该是这样的:

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

你应该考虑建立一个元注释共享最后两个注释,这样你就不必一遍又一遍地重复这个(三级?)。