gpt4 book ai didi

java - 使用@DataJpaTest 设置自定义方案

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:05:41 31 4
gpt4 key购买 nike

我想用 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 替换了 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 {
...
}

您应该考虑创建一个元注释来共享最后两个(三个?)注释,这样您就不必一遍又一遍地重复此操作。

关于java - 使用@DataJpaTest 设置自定义方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343822/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com