Question

I am unit testing my code using Powermock and Easymock. I have one method which internally calls the method which returns the Entity Manager object(which is initialized by spring). How do I mock this function from my junit code? Is there any other approach? Currently I have written a code which looks something like this

BaseJpaDaoImpl jpaDaoImplMock= EasyMock.createNiceMock(BaseJpaDaoImpl.class);
EasyMock.expect(jpaDaoImplMock.getEntityManager(true)).andReturn().anyTimes();
EasyMock.replay(jpaDaoImplMock);

BaseJpaDaoImpl contains the method which returns the Entity Manager instance.

protected EntityManager getEntityManager(boolean throwExceptionIfNotSet) {
    if(throwExceptionIfNotSet && entityManager == null) {
        logger.error("EM is NULL");
        throw new IllegalStateException("Deployment Issue, EM is Null!");
    }
    return entityManager;
}

which looks like this

Any help will be appreciated Thanks a lot!!

Attaching the test Class

@RunWith(PowerMockRunner.class)
@PrepareForTest({RequestContextHelperUtil.class, BaseJpaDaoImpl.class,SearchAwareBaseJpaDaoImpl.class})
public class InventoryDaoJpaImplTest {

@Test
public void ABC() throws Exception {

    PowerMock.mockStatic(RequestContextHelperUtil.class);
    BaseJpaDaoImpl jpaDaoImplMock= EasyMock.createNiceMock(BaseJpaDaoImpl.class);
    EasyMock.expect(jpaDaoImplMock.getEntityManager(true)).andReturn(null).anyTimes();
    EasyMock.replay(jpaDaoImplMock);
Was it helpful?

Solution

Finally, After a lot of head cracking I realized I had missed a small point. This is what I did

EntityManager em = EasyMock.createNiceMock(EntityManager.class);
BaseJpaDaoImpl jpaDaoImplMock = EasyMock.createNiceMock(BaseJpaDaoImpl.class);
EasyMock.expect(jpaDaoImplMock.getEntityManager(true)).andReturn(em).anyTimes();
EasyMock.replay(em);
EasyMock.replay(jpaDaoImplMock);

Simply mocked my response

Not the best of techniques,but I got what I was looking for.

Thanks for all who tried!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top