Below is the method from controller
@RequestMapping("addWorkout")
public String addWorkout(ModelMap modelmap,HttpSession session) {
LOGGER.info("Inside addWorkout,Start");
int userId=(int)session.getAttribute("userId");
// modelmap.addAttribute("userId",id);
List<Workout> workoutList = workoutRepo.findByUserId(userId,Sort.by(new Sort.Order(Direction.DESC, "date"), new Sort.Order(Direction.DESC, "startTime")));
modelmap.addAttribute("workoutList", workoutList);
modelmap.addAttribute("exerciseList", exerciseRepo.findAll());
LOGGER.info("Inside addWorkout,end");
return "AddWorkout";
}
How do i write when call for below line of code?it could be any simple type of match for SORT parameter
workoutRepo.findByUserId(userId,Sort.by(new Sort.Order(Direction.DESC, "date"), new Sort.Order(Direction.DESC, "startTime")));
Below is the test method i have written for the above controller method
@Test
void addWorkoutTest() {
int userId = 1;
List<Workout> mockWorkoutList = new ArrayList<>();
List<Exercise> mockExerciseList = new ArrayList<>();
when(exerciseRepo.findAll()).thenReturn(mockExerciseList);
when(session.getAttribute("userId")).thenReturn(userId);
String result = workoutController.addWorkout(modelMap, session);
verify(exerciseRepo, times(1)).findAll();
verify(session, times(1)).getAttribute("userId");
verify(modelMap, times(1)).addAttribute("workoutList", mockWorkoutList);
verify(modelMap, times(1)).addAttribute("exerciseList", mockExerciseList);
assertNotNull(result);
}`
i am unsure how to handle the SORT parameter part.Looking for different ways to handle the SORT parameter in when() call.Any examples will help me learn
when(workoutRepo.findByUserId(anyInt(), ) ).thenReturn(mockWorkoutList);
userId
is an int and Sort
overrides boolean equals(Object)
, so you can match directly on the exact arguments:
when(workoutRepo.findByUserId(userId, Sort.by(new Sort.Order(Direction.DESC, "date"), new Sort.Order(Direction.DESC, "startTime"))))
.thenReturn(List.of(…));
You can also use eq
matchers (Matchers.eq
):
when(workoutRepo.findByUserId(eq(userId), eq(Sort.by(new Sort.Order(Direction.DESC, "date"), new Sort.Order(Direction.DESC, "startTime")))))
.thenReturn(List.of(…));
or match with any()
if you don't care about the actual value:
when(workoutRepo.findByUserId(eq(userId), any()))
.thenReturn(List.of(…));