首页 > 解决方案 > 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.

我的测试有什么问题?

标签: javaspringjunit

解决方案


如果你想测试你的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);

所以你不应该在数据库中保存任何东西(实际上,当你进行单元测试时你根本不应该与数据库交互),你只是模拟你在服务上使用的存储库。这是我几个月前写的一个项目,我实际上解决了完全相同的问题。


推荐阅读