spring-boot - 使用 @DataJpaTest 进行集成测试
问题描述
我的项目中有这个测试:
@DataJpaTest
@SpringBootTest
@TestPropertySource(locations = "classpath:local-configuration.properties")
public class CanPixaRepositoryTest {
@Autowired
private CanPixaRepository canPixaRepository;
public void setUp() throws Exception {
}
@Test
public void testAll() {
canPixaRepository].getAvui("fqs");
}
}
本地配置.properties:
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
但是当我运行测试时, canPixaRepositoryRepository 为空
解决方案
对于 Spring 引导应用程序,如果您使用 JPA 和 Spring Data JPA,最简单的方法是使用带有 H2 的 @DataJpaTest 来测试您的存储库。
- 将 h2 依赖项添加到您的测试范围中。Spring Boot 将自动配置它并在测试阶段使用它来替换运行时 DataSource。
- 用 注释您的测试
@DataJpaTest
。然后EntityManager
,您的存储库和测试目的TestEntityManager
在 Spring 应用程序上下文中可用。
在这里查看我的示例。
(Spring 5/Spring Boot 2 添加了 Junit 5 支持,它不需要,@Runwith
或者@Extendwith
如果您正在使用 Junit 5 集成,DataJpaTest 本身是一个元注释,在 Spring 2.4 之前,要启用 Junit5,您必须从其中排除 JUnit 4 spring-boot-test 并手动添加 JUnit 5。在即将发布的 Spring Boot 2.4 中,JUnit 5 是默认的测试运行器)
推荐阅读
- python - 图像未在 Django 中转换为 base 64
- python - {{ self.article_title }} 标签没有出现在 wagtail 上的网络应用程序中
- java - JPA 没有为实体生成 ID
- docker - Docker Compose 文件:从另一个文件引用环境变量
- json - 使用 API 在 netsuite 中创建 salesOrder 的示例 JSON 格式
- python - 如何在 SerializerMethodField() 使用多个查询集优化 django-rest-framework 序列化器
- django - 如何在 StackedInline Django 中显示额外的动态字段以及所有模型字段
- c++ - 二维数组——“初始化器值太多”警告/错误
- c# - 检测到带有父母标签的孩子
- php - 通过 Redis 的 Laravel 队列:local.ERROR:连接到 127.0.0.1:6379 时出现读取错误