Search code examples
javajpacriteriapredicate

How to mock CriteriaQuery.where() followed by order by


I have the class where

CriteriaQuery<Entity> cq=criteriaQuery.root<Entity>();
.....
.....
cq.where(predictes.toArray(new Predicate[0])).orderBy(criteriaBuilder.asc(root.get(ENTITY.COLUMNNAME))

I need to mock this line , unable to pass this line. I tried

mockito.doReturn(Path).when(root).get(....);
mockito.doReturn(Order).when(criteriabuilder).asc(Path);

This also not helping me to acheive


Solution

  • I suggest to mock repository method instead of CriteriaQuery construction, with something like this in your mock class:

        @Mock
        CustomRepository customRepository;
        Mockito.when(customRepository.findEntity(Matchers.any()))
                .thenReturn(entity);