java - DataJpaTest 与单个自动装配测试 bean
问题描述
我想创建一个测试,它针对@Service
我项目中的一个服务类 ( )。
我的服务类有两种依赖:
- 其他服务,我想用
@MockBean
- JPA 存储库,我不想模拟;我希望它们是真正的 Spring bean,针对 H2 数据库进行配置
我的服务仅依赖于其他服务或存储库。存储库没有依赖关系——想象一下 JPA 存储库接口。
我想出了以下解决方案,效果很好:
@DataJpaTest
class FooServiceTests {
@Autowired
private FooRepository fooRepository;
@MockBean
private BarService barService;
@Test
void testService() {
FooService fooService = new FooService(barService, fooRepository);
Assertions.assertNotNull(barService);
Assertions.assertNotNull(fooRepository);
}
}
我的问题是,这个解决方案是否有替代方案,它不需要手动组装测试的 bean。一个解决方案,通过使用模拟服务和真实(H2)存储库,让 Spring 为我组装 bean。一种解决方案,它允许被测试的 bean 依赖@Autowired
于私有字段。像这样的东西:(显然不起作用):
@DataJpaTest
@ContextConfiguration(classes = FooService.class)
class FooService2Tests {
@MockBean
private BarService barService;
@Autowired
private FooService fooService;
@Test
void testService() {
Assertions.assertNotNull(fooService);
Assertions.assertNotNull(barService);
Assertions.assertNotNull(fooService.getBarService());
Assertions.assertNotNull(fooService.getFooRepository());
}
}
我想避免使用@SpringBootTest
. 如果某些答案表明是这样,那么它应该解释一下,为什么这是最好的方法。
解决方案
推荐阅读
- android - 在不询问用户的情况下自动安装应用程序
- python - 如果模型在时限内找不到解决方案,我该如何停止方法?
- r - 使用 R 在 ssh 服务器中加载文件
- c++ - 当我尝试在我的 codelite 项目中运行除 main.cpp 之外的任何 cpp 文件时,我在 codelite 中遇到错误
- javascript - 分隔数组内的元素
- javascript - 如何通过使用 onchange 方法更改下拉框中的值来将值从数据库获取到动态行
- python - 从 pytest 输出中删除 FAILURES
- maple - 如何在 Maple 中使用变量的值
- assembly - masm 中打印数字的 OFFSET 关键字
- php - 2 个日期之间不包括第一天