DEV Community

Lê Trọng Tân
Lê Trọng Tân

Posted on

Mockito Predicate JPA in unit testing not run correctly

2

In Unit Test Class:

    @Mock
    EntityManager entityManager
    @Mock
    Root<RedFox> redFoxRoot;

    @Mock
    Expression expression;

    @Mock
    Path path;

    @Mock
    Predicate predicate;

    @Test 
    public void filterTest(){
      TypedQuery<RedFox> redFoxQuery = (TypedQuery<RedFox>) Mockito.mock(TypedQuery.class);

      CriteriaQuery<RedFox> redFoxCriteriaQuery = Mockito.mock(CriteriaQuery.class);

      Mockito.when(redFoxCriteriaQuery.where(Mockito.any(Predicate[].class)))
      .thenReturn(redFoxQuery); 
 
      Mockito.when(redFoxCriteriaQuery.orderBy(Mockito.anyList())).thenReturn(redFoxCriteriaQuery);

      CriteriaBuilder builder = Mockito.mock(CriteriaBuilder.class);

      Mockito.when(redFoxRoot.get("isDeleted")).thenReturn(path);

      Mockito.when(path.isNull()).thenReturn(predicate);

      Mockito.when(builder.literal(Mockito.any())).thenReturn(expression);

      Mockito.when(redFoxCriteriaQuery.from(RedFox.class)).thenReturn(redFoxRoot);      
 
      Mockito.when(entityManager.createQuery(redFoxCriteriaQuery)).thenReturn(redFoxQuery);

      List<RedFox> redFoxs = new ArrayList<>();
      RedFox

Top comments (0)