使用@DataJpaTest 设置自定义方案
Setting up custom scheme using @DataJpaTest
我想用 Spring 启动测试存储库,并希望包含 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
取代了 your configured datasource by an in-memory data source。
如果您不想这样,junit
特殊配置文件显然就是这种情况,您需要指示 Spring 引导不要覆盖您配置的 DataSource
。我在上面给出的 link 中的文档中有一个示例。本质上,您的测试应如下所示:
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("junit")
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class MyRepositoryTest {
...
}
您应该考虑创建一个元注释来共享最后两个(三个?)注释,这样您就不必一遍又一遍地重复。
我想用 Spring 启动测试存储库,并希望包含 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
取代了 your configured datasource by an in-memory data source。
如果您不想这样,junit
特殊配置文件显然就是这种情况,您需要指示 Spring 引导不要覆盖您配置的 DataSource
。我在上面给出的 link 中的文档中有一个示例。本质上,您的测试应如下所示:
@RunWith(SpringRunner.class)
@DataJpaTest
@ActiveProfiles("junit")
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class MyRepositoryTest {
...
}
您应该考虑创建一个元注释来共享最后两个(三个?)注释,这样您就不必一遍又一遍地重复。