Issue
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.
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);
The method to be tested:
public void updateModuleStatusPerPlan(planId, userId){
planDetailRepository.findOngoingModules(planId, userId)
.forEach(userstatus -> {
userstatus.setStatus(1);
userStatusRepository.save(userstatus);
});
}
Solution
You should use Mockito to do it.You can mock planDetailRepository and userStatusRepository and then perform unit testing:
@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));
}
Try this and let me know in case of exceptions...
Answered By - codeLover
Answer Checked By - Pedro (JavaFixing Volunteer)