Java 使用@DataJpaTest设置自定义方案

Java 使用@DataJpaTest设置自定义方案,java,spring-boot,junit,h2,jpa-2.1,Java,Spring Boot,Junit,H2,Jpa 2.1,我想用Spring Boot测试一个存储库,并想包括TestEntityManager来检查存储库是否真的做了它应该做的事情 这就是JUnit测试: @RunWith(SpringRunner.class) @DataJpaTest public class MyRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private MyRepository

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

这就是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文件来设置表

提前感谢,,
尼娜

这不是因为
@DataJpaTest
取代了

如果您不想这样做,这显然是那种
junit
特殊配置文件的情况,那么您需要指示Spring Boot不要覆盖配置的
数据源。在我上面给出的链接中的文档中有一个例子。基本上,您的测试应该如下所示:

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

你应该考虑创建一个元注释来共享最后两个(三)注释,这样你就不必一次又一次重复这个。