开发者

How to mock EntityManager? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. 开发者_运维问答

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

Closed 5 months ago.

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜