Reputation: 4531
I'm trying to write JUnit tests for a stateless session bean that has an injected EntityManager:
@Stateless
public class MyServiceBean implements MyService, ... {
@PersistenceContext
private EntityManager em;
....
Of course, without doing anything, em remains null in the flow of the test...
The tests should run standalone (NOT in a Java EE container).
How do I do that please? (simple solutions will be most appreciated :-)
Upvotes: 6
Views: 11285
Reputation: 12728
You mock it with Mockito. You add dependency of Mockito and with @MockitoJUnitRunner
annotation on your class, you can @Mock EntityManger entityManager
and @InjectMocks MyService service
in your unit test. You will stub it like when(entityManager.findById(id)).thenReturn(somethingIWantItToReturn);
.
Upvotes: 0
Reputation: 4941
If you want to test your data access logic (criteria code, jpql queries, etc) what I'd do is using HSQLDB. There is no need to mock the EntityManager or have a Java EE container and it integrates nicely with the build process.
Upvotes: 0
Reputation: 5792
Simple answer is don't do that, if you want to have persistence context injected like in the real working application, use embedded/external server for testing. More info about testing EJBs and JPA you can find here: Best current framework for unit testing EJB3 / JPA
Upvotes: 3