Issue
JUNIT Test How To Mock Entity Manager Factory. i'm writing junit test case for Entity Manager Factory but here in side when (when().then()) getting null.
Solution
Add @ExtendWith(MockitoExtension.class)
at the top of you Test class.
This code is working for me. You should remove @ExtendWith (SpringExtension.class). Also remove that Mockito.mock since we have added @Mock on top of those fields.
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class TestClass {
@Mock
private EntityManager entityManager;
@Mock
private EntityManagerFactory entityManagerFactory;
@Mock
private CriteriaBuilder criteriaBuilder;
@Mock
private CriteriaQuery<User> criteriaQuery;
@Test
void getSearchData() {
when(entityManagerFactory.createEntityManager()).thenReturn(entityManager);
when(entityManager.getCriteriaBuilder()).thenReturn(criteriaBuilder);
when(criteriaBuilder.createQuery(User.class)).thenReturn(criteriaQuery);
when(criteriaQuery.from(User.class)).thenReturn(new Root<>());//you can also mock Root object
}
}
Answered By - Sagar Rawat
Answer Checked By - Pedro (JavaFixing Volunteer)