Problem:
I'm trying to create a test, using Mockito. This test Mocks a QueryBuilder and try to verify if everything is ok. But I am getting "java.lang.NullPointerException" . It seems like something hasn't been initialized, but i can't see what it is.
Code:
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class AcademicJPADAOTest {
@Mock
private EntityManager entityManager;
@Mock
private CriteriaBuilder cb;
@Mock
private CriteriaQuery<Academic> cq;
@Mock
private Root<Academic> root;
@InjectMocks
AcademicJPADAO academicjpadao;
private String passwdcode = "83997689-22b6-4a7e-a801";
@Test
public void retrieveByPasswordCodeTest() throws PersistentObjectNotFoundException, MultiplePersistentObjectsFoundException {
Academic academic = new Academic();
when(entityManager.getCriteriaBuilder()).thenReturn(cb);
when(cb.createQuery(Academic.class)).thenReturn(cq);
when(cq.from(Academic.class)).thenReturn(root);
when(cq.where(cb.equal(root.get(Academic_.passwordCode), passwdcode))).thenReturn(cq);
when(academicjpadao.getEntityManager().createQuery(cq).getSingleResult()).thenReturn(academic);
academicjpadao.retrieveByPasswordCode(passwdcode);
verify(entityManager, times(1)).getCriteriaBuilder();
}
}
Line error:
when(academicjpadao.getEntityManager().createQuery(cq).getSingleResult()).thenReturn(academic);
Maybe your academicjpadao
isn't injected correctly in this part:
@InjectMocks
AcademicJPADAO academicjpadao;
so Use MockitoAnnotations.initMocks
to initiate the @Mock
and @InjectMocks
objects.so you have to add to your class this method:
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.