java - 在集成测试中使用 Autowire 进行数据库测试
问题描述
我是数据库测试的新手,我正在尝试通过在类级别使用标签 @SpringBootTest 并使用 Autowire 来连接数据库,它不会创建始终为空的实例化
@SprintBootTest
Class Test{
@Autowire
DatabaseService databaseService;
}
有人可以建议吗?如果有人做过类似的事情,请给我指导
解决方案
有多种方法可以测试您的数据库,这里有几种方法,
使用 h2(in-memory-DB) 来模拟数据库非常好。虽然这不是强制性的,我们也可以使用mockito来模拟数据库交互。
添加这些依赖项,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.196</version>
<scope>test</scope>
</dependency>
现在你的测试类应该是这样的,
@RunWith(SpringRunner.class)
@SpringBootTest(classes = YourApp.class, webEnvironment = RANDOM_PORT)
Class DatabaseServiceTest{
@Autowired
private DatabaseService databaseService;
}
复制实际的数据库配置属性
首先,您需要将您的 properties/yml 从目录复制main/resources
到test/resources
目录。您的测试类与上述方法中给出的相同。但请确保你h2-dependency
从你的 pom.xml 中排除了。
请同时探索这些教程,
推荐阅读
- reactjs - 如何使用 jest-sonar-reporter?
- git - git: 'remote-addhttps' 不是 git 命令。见'git --help'
- deep-learning - 在自定义数据集的 yolo 训练期间重写框是什么意思?
- c++ - 两个链表的交点
- python - 多渠道漏斗 API - 未知 API 或版本
- javascript - 使用 vue js 进行网页抓取
- c++ - x86 中的下划线前缀问题:从 C++ 函数调用 NASM 函数在 x64 中有效,但在 x86 中失败
- python - ValueError:您传递给模型的 Numpy 数组列表不是模型预期的大小
- java - 将单个 Spring bean 实例注入实用程序类的静态变量
- javascript - 在 Jupyter 笔记本中运行的单元格期间,pandas 表中的变量未更新:从 javascript 调用 python 函数时出现问题