Junit - Testing a method that uses Foreach

How do I write a unit for the method below?

Basically the planDetailRepository.findOnGoingModules method returns a list of UserStatus entity then apply forEach method on that list setting the status to 1 then save the current UserStatus entity to the database.

My idea of testing this is to verify the UserStatusRepository save method number of times it's been called.


@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);

The method to be tested:

public void updateModuleStatusPerPlan(planId, userId){
        planDetailRepository.findOngoingModules(planId, userId)
                .forEach(userstatus -> {

1 answer

  • answered 2018-07-11 05:59 Garima Gupta

    You should use Mockito to do it.You can mock planDetailRepository and userStatusRepository and then perform unit testing:

    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);
          <<your class object>>.updateModuleStatusPerPlan(planId, userId);//Set any plan id or user id which should be the same as used while mocking planDetailRepositoryMock.findOngoingModules

    Try this and let me know in case of exceptions...