How to mock EntityManager?

Muhammad Hewedy picture Muhammad Hewedy · Nov 28, 2010 · Viewed 35.9k times · Source

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

Answer

Koitoer picture Koitoer · Jan 14, 2014

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