Danilo M.
Danilo M.

Reputation: 1592

Session comes null using mockito to test DAO

I am using Mockito to do my DAO test, but when I call the method save which has a session: Session session = (Session) getEntityManager().getDelegate();, but the session comes null, I dont know what is happening, someone could help me ??

Mockito.when(MyDAOImplMock.salvarOuEditar(object)).thenReturn(object);
objectTest = MyDAOImpl.salvarOuEditar(object);
Mockito.verify(MyDAOImplMock).salvarOuEditar(object);

MyDAOImplMock is a mock of my DAO implementation, and MyDAOImpl is a instance of my DAO implementation.

@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public T salvarOuEditar(T entidade) {
    Session session = (Session) getEntityManager().getDelegate();
    session.saveOrUpdate(entidade);
    return entidade;
}

Upvotes: 1

Views: 1145

Answers (1)

Danilo M.
Danilo M.

Reputation: 1592

@Autowired
private MyDAOImpl myDAOImpl;

@PersistenceContext
private EntityManager entityManager;

@Before
public void init() {
    myDAOImpl.setEntityManager(entityManager);
    objectTeste = new MyObject();
    object = new MyObject();
}

@Test
    public void testSave() {
    objectTeste = myDAOImpl.salvarOuEditar(object);
    Assert.assertEquals(objectTeste, object);
    Assert.assertEquals(object.getId(), objectTeste.getId());
}

This way the session is not coming null ! Thanks for all !

Upvotes: 1

Related Questions