2016-12-27 80 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 { 
    ... 
} 

你應該考慮建立一個元註釋共享最後兩個註釋,這樣你就不必一遍又一遍地重複這個(三級?)。