Question

I need to mock entity-manager to make testing service layer (in my case a session facade) to be independent of the underlying layer (which in my case is the entity-manager).

So how I can accomplish this? Should I use dbunit? Do I need easy/j(Mock)?

Was it helpful?

Solution

I suggest to use Mockito Framework it is very easy to use and understand.

@Mock
private EntityManager entityManager; 

If you want to use any method that belongs to entityManager, you should call.

Mockito.when(METHOD_EXPECTED_TO_BE_CALLED).thenReturn(AnyObjectoftheReturnType);

When you run your test, any call previosly declared in the Mockito.when for the EntityManager will return the value put in the declaration..

Read full documentation here.

https://static.javadoc.io/org.mockito/mockito-core/2.12.0/org/mockito/Mockito.html#stubbing

OTHER TIPS

For mocking, I'd suggest powermock. Thanks to auto generated proxies, it can do virtually anything you can imagine, starting with creating mocks from interfaces, through intercepting initialization finishing with suppressing static initialization (the only thing that beat me was messing with mocking java.lang.Object).

Let's say the SessionFacadeTest is your JUnit test suite for SeesionFacade.

import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.replayAll;
import static org.powermock.api.easymock.PowerMock.verifyAll;
import static org.easymock.EasyMock.anyObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.persistence.EntityManager;

@RunWith(PowerMockRunner.class)
@PrepareForTest({SessionFacade.class})
public class SessionFacadeTest {
    @Test public void persistingObject() {
        //set up stage
        SessionFacade fixture = new SessionFacade();
        EntityManager managerMock = createMock(EntityManager.class);
        fixture.setManager(managerMock);
        //record expected behavior
        managerMock.persist(anyObject());
        //testing stage
        replayAll();
        fixture.anyMethodThatCallPersist();
        //asserting stage
        verifyAll();
    }
}

(Note: I wrote it here, so may even not compile, but shall give you the idea).

I'm usually using EasyMock for mocking concrete service implementation in test cases. Check out their user guide. It includes a a very easy to follow step-by-step guide, which explains the basic concepts behind mocking frameworks in general and gets you up and running with EasyMock fast.

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