Junit-测试使用Foreach

时间:2018-07-11 02:58:41

标签: spring-boot junit

如何为以下方法编写一个单位?

基本上 planDetailRepository.findOnGoingModules 方法返回 UserStatus 实体的列表 然后在该列表上应用forEach方法,将状态设置为1,然后保存当前的 UserStatus 实体 到数据库。

我对此进行测试的想法是验证 UserStatusRepository 保存方法被调用的次数。

planDetailRepository.findOnGoingModules:

@Query("SELECT a FROM UserStatus a join a.planDetail b where b.startDate = CURRENT_DATE AND a.userPlan.id = (SELECT c.id from UserPlan c WHERE c.plan.id = :plan_id and c.user.id = :user_id)")
    List<UserStatus> findOngoingModules(@Param("plan_id") Integer plan_id, @Param("user_id") Integer user_id);

要测试的方法:

public void updateModuleStatusPerPlan(planId, userId){
        planDetailRepository.findOngoingModules(planId, userId)
                .forEach(userstatus -> {
                    userstatus.setStatus(1);
                    userStatusRepository.save(userstatus);
                });
    }

1 个答案:

答案 0 :(得分:1)

您应该使用 Mockito 进行操作。您可以模拟planDetailRepository和userStatusRepository,然后执行单元测试:

@Test
public void testUpdateModuleStatusPerPlan()    {
      List<UserStatus> userStatusList=new ArrayList<UserStatus>();
      //Create new User Status objects and add them to list
      when(planDetailRepositoryMock.findOngoingModules(planId, userId)).thenReturn(userStatusList);
      when(userStatusRepositoryMock.save(Matchers.any(UserStatus.class)).thenReturn(null);
      <<your class object>>.updateModuleStatusPerPlan(planId, userId);//Set any plan id or user id which should be the same as used while mocking planDetailRepositoryMock.findOngoingModules
      verify(userStatusRepositoryMock,times(userStatusList.size()).save(Matchers.any(UserStatus.class));
}

尝试此操作,如有例外,请通知我...