Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock EntityManager?

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

like image 384
Muhammad Hewedy Avatar asked Nov 28 '10 08:11

Muhammad Hewedy


People also ask

How do I test entity manager?

What you need to insert is a query mock... @Mock private Query query; ... // when createQuery is called, return the mocked query object (instead of null) when(entityManager. createQuery(any(String. class)).

How do you mock persistence?

You can simply test your setId() and getId() methods for Article class. I think there is no need to mock EntityManager and tell it to set id to article. This test will be more suitable when unit testing EntityManager itself, when you want to check if id is generated and set to entity you pass to persist.


1 Answers

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

like image 131
Koitoer Avatar answered Sep 19 '22 12:09

Koitoer