title: Mocking Entitymanager while testing of EJB class
body: <p>I am using: Netbeans, Glassfish, Mockito</p>
  
  <p>While working with Java EE for the first time I have come across the issue of trying to test methods that interact with the database using an entitymanager.</p>
  
  <p>In the below code snippets I have tried to mock out the entity manager so i know that the db interaction will not be tested exactly and for this testing thats ok. But I am striggling on instansiating the <code>UsersController</code> because it has an injected <code>EntityManager</code> which is always <code>null</code>. I would like the <code>EntityManager</code> to be mocked out so I can test the rest of the method.</p>
  
  <p>Below is a class that interacts with the db. NOTE this is an example methods, it is not for use in production.</p>
  
  <pre><code>@Stateless
  public class UsersController {
      @PersistenceContext()
      EntityManager em;
  
      public User getOne() {
          em.getEntityManagerFactory().getCache().evictAll();
          User theUser = null;
          try {
              Query q = em.createNamedQuery("User.findAll");
              Collection&lt;User&gt; entities = q.getResultList();
              theUser = Iterables.get(entities, 1);
          }
          catch(NoResultException e){}
          em.flush();
          return theUser;
      };
  }
  </code></pre>
  
  <p>The test file that will test this method.</p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  public class UsersControllerTest {
  
      @Mock
      private UsersController usersController;
      @Mock
      private EntityManager entityManagerMock;
  
      private Collection&lt;User&gt; mockUsersDbCollection = //...
  
      @BeforeClass
      public void setUpClass() {
  
          when(entityManagerMock.createNamedQuery("User.findAll")).thenReturn(mockUsersDbCollection);
      }
  
      @Test
      public void findOneTest(){
          User mockUserDbEntry = new User("1", "pa$$word", "salt", "user1", "user1@email.com", false);
  
          User returnedUser = null;
          returnedUser = usersController.getOne();
  
          assertEquals(returnedUser.getId(), "1");
      }
  }
  </code></pre>
  
  <p>Whenever the <code>UsersController</code> mock is created the entityManager is always null causing issues, how can I inject the <code>EntityManagerMock</code> so it will work?</p>