How to mock EntityManager?

你。 提交于 2020-12-30 04:49:43

问题


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)?


回答1:


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




回答2:


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).




回答3:


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.



来源:https://stackoverflow.com/questions/4296042/how-to-mock-entitymanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!