5

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

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
Hagai Cibulski
  • 4,421
  • 3
  • 20
  • 23

3 Answers3

4

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

Community
  • 1
  • 1
Kris
  • 5,714
  • 2
  • 27
  • 47
0

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

WesternGun
  • 11,303
  • 6
  • 88
  • 157
0

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.

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140