java - Spring Junit 测试实体未保存到存储库
问题描述
我正在尝试测试列出所有实体的服务方法。该方法如下所示:
@Test
public void listAllProfiles() {
Profile sampleProfile = Profile.createWithDefaultValues();
profileRepository.save(sampleProfile);
ProfileService profileService = new ProfileService(profileRepository, new ModelMapper());
List<ProfileDto> profiles = profileService.listAllProfiles();
ProfileDto lastProfile = profiles.get(profiles.size() - 1);
assertEquals(sampleProfile.getId(), lastProfile.getId());
}
测试失败原因IndexOutOfBoundsException: Index -1 out of bounds for length 0
我发现sampleProfile
在测试期间可能没有保存。当我登录时profileRepository.findAll().size()
,该值始终为0
.
我的测试有什么问题?
解决方案
如果你想测试你的ProfileService
,你必须模拟profileRepository
原因,如果你不这样做,那么你实际上是在做一个集成测试。
单元测试就是测试小单元,如果你必须模拟它们(手动或使用框架,Mockito是 Java 世界中最常见的)。
如果您的服务正在使用存储库来获取您必须模拟该调用的所有配置文件,如下所示:
List<Profile> profilesList = Arrays.asList(new Profile("Profile 1"), new Profile("Proiile 2"));
given(profileRepository.findAll()).willAnswer((Answer<List>) invocation -> profilesList);
所以你不应该在数据库中保存任何东西(实际上,当你进行单元测试时你根本不应该与数据库交互),你只是模拟你在服务上使用的存储库。这是我几个月前写的一个项目,我实际上解决了完全相同的问题。
推荐阅读
- javascript - 使用 html 5 视频标签以角度播放本地视频时清理不安全的 URL
- node.js - 从 node.js 应用程序调用 aws lambda 函数会出现 AccessDeniedException 错误
- sql - Access SQL:从插入语句或从 DAO.QueryDef 获取受影响记录的标识值
- visual-studio-2015 - SSIS 2015 无法创建数据源
- r - 从 R 中的 RGB 数据帧中保存多个 PNG
- c# - 如何解决此错误:RabbitMQ.Client.Exceptions.BrokerUnreachableException: 'None of the specified endpoint were reachable'
- drupal - Drupal 8 孤儿段落
- mysql - nodejs Sequelize bulkCreate() 模型错误验证不起作用
- erlang - 无法使用 erlang httpc:request 将数据发布到 web 服务
- angular - 角度向下和向上滑动动画