java - @Autowired 和 @SpringBootTest 应该在单元测试中使用吗?
问题描述
在我工作的一个项目中,我们一直在通过以下方式初始化单元测试服务:
- 服务所需的模拟依赖项。
- 使用构造函数创建服务。
像这样的东西:
@RunWith(SpringRunner.class)
public class ServiceTest extends AbstractUnitTest {
@Mock private Repository repository;
private Service service;
@Before
public void init() {
service = new Service(repository);
when(repository.findById(any(Long.class))).thenReturn(Optional.of(new Entity()));
}
}
但是我们的新开发人员建议使用@Autowired
和@SpringBootTest
@SpringBootTest(classes = ServiceTest.class)
@MockBean(classes = Repository.class)
@RunWith(SpringRunner.class)
public class ServiceTest extends AbstractUnitTest {
@MockBean private Repository repository;
@Autowired private Service service;
@Before
public void init() {
when(repository.findById(any(Long.class))).thenReturn(Optional.of(new Entity()));
}
}
@Autowired
在此之前,我认为@SpringBootTest
应该只在集成测试中使用。但是google了很多,我看到有些人在单元测试中使用这两个。我读了boot-features-testing。另外,我阅读了这篇单元测试与 Spring 的集成测试。对我来说,我们仍然觉得需要 Spring 来为单元测试做依赖注入并不好,因为我们可以自己做这个来做单元测试。那么,应该@Autowired
并且@SpringBootTest
在单元测试中使用?
解决方案
不会。单元测试是单独测试单个组件。在你的 bean 中使用构造函数注入可以让你非常简单地调用new SomeService(myMock)
,不需要 Spring。
编写组件或功能测试(测试您的应用程序但不将其连接到外部服务以进行完整的集成测试,仅模拟外部接口;这对于 MockMvc 测试之类的东西很有用)非常适合@SpringBootTest
,在这种情况下,您可能需要在 Spring 配置中创建模拟对象并将它们自动连接到您的测试中,以便您可以操作它们。
推荐阅读
- css - 伪元素 css 背景覆盖 - 导致奇怪的线条渲染
- python - 导出到excel时Pandas打印订单列
- java - java.lang.OutOfMemoryError:Java heap Space error after building app in Jenkins
- python - 为什么枚举列表以从中删除项目有效?
- node.js - node.js 异步日志记录和未处理的服务器异常的最佳实践
- raspberry-pi - GitPython 获取 Github 存储库状态
- flutter - Flutter 3D Cube 旋转变换矩阵(如 Instagram 故事)
- java - 找出前两位数字和后两位数字之和的平方等于数字本身的所有四位数字
- apache-kafka - 如何使用 Kafka 控制台生产者处理压缩数据
- reactjs - 如何为 React 服务