私が使用していながら:Netbeansの、Glassfishの、MockitoモッキングEntityManagerのEJBクラスのテストは
私は、データベースを使用して対話するメソッドをテストしようとしているの問題に遭遇したのは初めてのためのJava EEでの作業中entitymanager。
以下のコードスニペットでは、エンティティマネージャをモックアウトしようとしていますので、dbのやりとりは正確にテストされず、このテストは正常です。しかし、私はUsersController
を注入することに夢中になっています。なぜなら、注入されたEntityManager
は常にnull
です。 EntityManager
を嘲笑して、残りのメソッドをテストできるようにしたいと思います。
以下は、dbとやり取りするクラスです。これはサンプルメソッドであることに注意してください。これは本番用ではありません。
@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<User> entities = q.getResultList();
theUser = Iterables.get(entities, 1);
}
catch(NoResultException e){}
em.flush();
return theUser;
};
}
このメソッドをテストするテストファイル。 UsersController
モックはEntityManagerを作成されるたびに
@RunWith(MockitoJUnitRunner.class)
public class UsersControllerTest {
@Mock
private UsersController usersController;
@Mock
private EntityManager entityManagerMock;
private Collection<User> 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", "[email protected]", false);
User returnedUser = null;
returnedUser = usersController.getOne();
assertEquals(returnedUser.getId(), "1");
}
}
は、どのように私はそれが動作しますので、EntityManagerMock
を注入することができ、常にnull原因の問題でしょうか?
フィードバックをいただきありがとうございますが、まだ問題が発生しています。 'em.getEntityManagerFactory()。getCache()。evictAll();'を呼び出すときにnullポインタ例外がありますが、entityManagerが擬似的に外されていると思いましたか? –
うん、その行を逃した。すべてのモックのデフォルトの動作は何もせず、必要に応じて 'null'または' 0'を返すことです。 –