I'm starting my test using mockito. first of all i need to test .findAll() that is a CriteriaQuery...
UserFacade extends AbstractFacade which have this findAll .
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
....
public List<T> findAll() {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(entityClass);
Root<T> rootEntry = cq.from(entityClass);
CriteriaQuery<T> all = cq.select(rootEntry);
TypedQuery<T> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
...
My test:
@RunWith(MockitoJUnitRunner.class)
public class UserFacadeTest {
public UserFacadeTest() {
}
@Mock
private EntityManager mockedEM;
@Mock
private CriteriaQuery mockedCQ;
@Mock
private CriteriaQuery mockedCQAll;
@Mock
private Root mockedRoot;
@Mock
private CriteriaBuilder mockedCB;
@Mock
private TypedQuery mockedTQ;
private UserFacade userFacade;
List<User> userList= new ArrayList<>();
@Before
public void setUp() {
userFacade=new UserFacade();
userFacade.setEm(mockedEM);
when(mockedEM.getCriteriaBuilder()).thenReturn(mockedCB);
when(mockedCB.createQuery()).thenReturn(mockedCQ);
when(mockedCQ.from(User.class)).thenReturn(mockedRoot);
when(mockedCQ.select(mockedRoot)).thenReturn(mockedCQAll);
when(mockedEM.createQuery(mockedCQAll)).thenReturn(mockedTQ);
when(mockedTQ.getResultList()).thenReturn(userList);
}
@Test
public void testFindAll() {
System.out.println("findAll");
User user = new User(1, "username", "password", "email", new Date());
userFacade.create(user);
verify(mockedEM, times(1)).persist(any());
userList.add(user);
//next line cause NullPointerException
List list=userFacade.findAll();
assertTrue("Should return 1", 1==list.size());
}
debugging my test i saw this:
....
public List<T> findAll() {
CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery<T> cq = cb.createQuery(entityClass); //cq is null!!!!
Root<T> rootEntry = cq.from(entityClass); //cq is null!!!!
CriteriaQuery<T> all = cq.select(rootEntry);
TypedQuery<T> allQuery = em.createQuery(all);
return allQuery.getResultList();
}
...
so i think i'm wrong passing "User.class"... i've to mock this too??? how?
Aucun commentaire:
Enregistrer un commentaire