Mockito Predicate JPA 不 运行 正确

Mockito Predicate JPA not run correctly

在单元测试中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 redFox = new RedFox();
      redFox.setTitle("abc");
      redFox.setRedFoxStatus("");
      redFox.setId(UUID.randomUUID());
      redFoxs.add(redFox);
   
      Mockito.when(redFoxQuery.getResultList()).thenReturn(redFoxs);
      
  }

在 class 服务中:

     public List<RedFox> filter(){
            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaQuery<RedFox> redFoxCriteriaQuery = builder.createQuery(RedFox.class);
            Root<RedFox> root = redFoxCriteriaQuery.from(RedFox.class);
            redFoxCriteriaQuery.select(root);
            List<Predicate> searchClause = new ArrayList<>();

            searchClause.add(builder.isFalse(root.get("isDeleted")));//root cause error

            Predicate[] searchClauses = searchClause.toArray(Predicate[]::new);
            Query executingQuery = em.createQuery(redFoxCriteriaQuery.where(searchClauses)
                                   .orderBy(orderBys));//Null pointer exception
            List<RedFox> resultData = executingQuery
                    .getResultList();
            ..............................
}

我的问题是当我评论searchClause.add(builder.isFalse(root.get("isDeleted")))时,这意味着searchClauses是空数组,然后代码执行成功。

但是当搜索子句不为空时,那么redFoxCriteriaQuery.where(searchClauses)就不会使用我mock的结果而是returnnull,会导致空指针异常

我被困了 2 天,但仍然不知道为什么,所以请帮我解决这个问题。

改变

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

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

因此,它可以处理任何非空对象。 但是如果你写 Mockito.any(Predicate[].class),那么它只是将 2 数组与 Predicate 类型进行比较。当然,虽然每个数组中的所有元素都相等,但 2 数组不能相等。