gpt4 book ai didi

java - 使用 JPATest 和 MongoDB 测试为 Polyglot Springboot 编写测试

转载 作者:行者123 更新时间:2023-11-28 21:16:25 25 4
gpt4 key购买 nike

我正在设置一个新的 Springboot 2 应用程序,它同时使用 MYSQL 数据库和 MongoDB 数据库进行数据存储。

我无法理解如何为同时使用 DataJPA 和 DataMongo 的测试编写类。

通过使用同时使用 JPA 存储库和 Mongo 存储库的服务,在两者之间设置查询以供实际使用是一项相对简单的任务。

在编写测试用例时,我能够只为 JPA 实体(@DataJPATest)或仅为 Mongo 实体(@DataMongoTest)编写测试轻松使用 H2 和嵌入式 Mongo。

不可能同时使用 JPA 和 Mongo 注释定义测试类,因为 Spring 只允许 1 个 Bootstrap 。

这是来自 JPA MYSQL 的类:

@Entity
@Data
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Size(max = 255)
private String name;

@Size(max = 1000)
private String description;
}

Mongo Repos 类:

@Document
@Data
public class Review {

@Id
private String id;

@Indexed
private String title;

private String reviewText;

private boolean recommended;

@Indexed
private Integer productId;

@DBRef
private List<Comment> comments;
}

@Document
@Data
public class Comment {

@Id
private String id;

private String title;

private String commentText;
}

示例预期测试类:

@RunWith(SpringRunner.class)
@DataJpaTest
@DataMongoTest
public class ReviewRepositoryTests {

@Autowired
TestEntityManager entityManager;

使用 DataJPA 和 DataMongo 编写测试类会导致此堆栈错误:

java.lang.IllegalStateException: Configuration error: found multiple declarations of @BootstrapWith for test class [xyz.cybersapien.tech.reviews.ReviewRepositoryTests]: [@org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTestContextBootstrapper)]

at org.springframework.test.context.BootstrapUtils.resolveExplicitTestContextBootstrapper(BootstrapUtils.java:166)
at org.springframework.test.context.BootstrapUtils.resolveTestContextBootstrapper(BootstrapUtils.java:127)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:124)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:142)

最佳答案

尝试使用 @SpringBootTest 而不是 @DataJpaTest@DataMongoTest

@RunWith(SpringRunner.class)
@SpringBootTest
public class ReviewRepositoryTests {

@Autowired
TestEntityManager entityManager;

官方 Spring Boot 文档 - https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html

关于java - 使用 JPATest 和 MongoDB 测试为 Polyglot Springboot 编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346516/

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