There is a basic CRUD API, and I want to test the UserServiseImpl.java class in its Service layer. In UserServiseImpl, entities are retrieved with
userRepository.findAll(query)
as shown below, and I want to mock this.
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
UserSpecification spec = new UserSpecification();
Specification<User> query = Specification.where(spec.userIdEqual(spec.userIdEqual(userId)))
.and(spec.nameContains(target.getName()))
.and(spec.startDateGreaterThanEqual(target.getStartDate()))
.and(spec.endDateLessThanEqual(target.getEndDate()))
List<User> user = userRepository.findAll(query);
I thought I could mock it with @Mock from Mockito as follows, but it seems that the instance of Specification (the argument query of findAll) cannot be the same instance that is specified when it is actually called, resulting in findAll being called with different arguments.
UserSpecification spec = new UserSpecification();
Specification<User> query = Specification.where(spec.userIdEqual("1"))
.and(spec.nameContains("john")
.and(spec.startDateGreaterThanEqual("2024-1-1"))
.and(spec.endDateLessThanEqual("2024-1-2"))
when(userRepository.findAll(query)).thenReturn(userList)
How should I mock in cases where Specification is used like this? If anyone knows, I would appreciate your guidance.