我正在设置一个新的 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 Test 为 Polyglot Springboot 编写测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346516/