My predicate returns null pointer when it is executed.
My test code:
public class CompanyRepositoryTest {
@Mock
private EntityManager entityManager;
@Mock
private CriteriaBuilder criteriaBuilder;
@Mock
private CriteriaQuery<Company> criteriaQuery;
@Mock
private Root<Company> root;
@Mock
private TypedQuery<Company> typedQuery;
@Mock
private Path<Object> path;
@Mock
private Expression<Object> express;
@InjectMocks
private CompanyRepositoryImpl companyRepository;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
@DisplayName("Should find Company by CNPJ and return success")
void findByCnpjSuccess() {
String cnpj = "123456789";
Company company = new Company();
company.setCnpj(cnpj);
List<Company> companies = new ArrayList<>();
companies.add(company);
when(entityManager.getCriteriaBuilder()).thenReturn(criteriaBuilder);
when(criteriaBuilder.createQuery(Company.class)).thenReturn(criteriaQuery);
when(criteriaQuery.from(Company.class)).thenReturn(root);
when(root.get("cnpj")).thenReturn(path);
Predicate predicate = mock(Predicate.class);
when(criteriaBuilder.and(any())).thenReturn(predicate);
when(criteriaBuilder.equal(path, cnpj)).thenReturn(predicate);
// Criando o Predicate corretamente
// Predicate predicate = criteriaBuilder.equal(root.get("cnpj"), cnpj);
// Configurando o mock para retornar o Predicate criado
// when(criteriaBuilder.equal(root.get("cnpj"), cnpj)).thenReturn(predicate);
when(entityManager.createQuery(criteriaQuery)).thenReturn(typedQuery);
when(typedQuery.getResultList()).thenReturn(companies);
List<Company> result = companyRepository.findByCnpj(cnpj);
assertEquals(1, result.size());
assertEquals(cnpj, result.get(0).getCnpj());
verify(entityManager).getCriteriaBuilder();
verify(criteriaBuilder).createQuery(Company.class);
verify(criteriaQuery).from(Company.class);
verify(criteriaBuilder).equal(root.get("cnpj"), cnpj);
verify(entityManager).createQuery(criteriaQuery);
verify(typedQuery).getResultList();
}
}
And my method tested
@Autowired
private EntityManager manager;
@Override
public List<Company> findByCnpj(String cnpj) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<Company> query = builder.createQuery(Company.class);
Root<Company> root = query.from(Company.class);
Predicate predicate = builder.and(builder.equal(root.get("cnpj"), cnpj));
query.select(root).where(predicate);
TypedQuery<Company> typedQuery = manager.createQuery(query);
return typedQuery.getResultList();
}
I'm trying to execute a test with Mockito.
A quick run through the code and I see that the "query.select(root)" is not mocked. You can try this:
when(criteriaQuery.select(root)).thenReturn(criteriaQuery);