如何在单元测试期间注入PersistenceContext? [英] How to inject PersistenceContext during unit testing?

查看:211
本文介绍了如何在单元测试期间注入PersistenceContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的java类:

  public class Finder {
@PersistenceContext(unitName =abc)
EntityManager em;
public boolean exists(int i){
return(this.em.find(Employee.class,i)!= null);


$ / code $ / pre

这是单元测试:

  public class FinderTest {
@Test public void testSimple(){
Finder f = new Finder();
assert(f.exists(1)== true);






测试失败,出现 NullPointerException 因为 Finder.em 不被任何人注入。我应该如何正确处理这种情况?是否存在最佳实践?

解决方案

没有像Spring这样的容器(或者类似于 Unitils - 这是基于Spring的),你将不得不手动注入实体管理器。在这种情况下,你可以使用类似这样的基类:

  public abstract class JpaBaseRolledBackTestCase { 
保护静态EntityManagerFactory emf;

受保护的EntityManager em;

@BeforeClass
public static void createEntityManagerFactory(){
emf = Persistence.createEntityManagerFactory(PetstorePu);


@AfterClass
public static void closeEntityManagerFactory(){
emf.close();
}

@Before
public void beginTransaction(){
em = emf.createEntityManager();
em.getTransaction()。begin();


$ b $ public void rollbackTransaction(){
if(em.getTransaction()。isActive()){
em.getTransaction() ).rollback();
}

if(em.isOpen()){
em.close();
}
}
}


This is my java class:

public class Finder {
  @PersistenceContext(unitName = "abc")
  EntityManager em;
  public boolean exists(int i) {
    return (this.em.find(Employee.class, i) != null);
  }
}

This is the unit test:

public class FinderTest {
  @Test public void testSimple() {
    Finder f = new Finder();
    assert(f.exists(1) == true);
  }
}

Testing fails with NullPointerException since Finder.em is not injected by anyone. How should I handle this situation properly? Does there any best practice exist?

解决方案

Without a container like Spring (or something like Unitils - which is Spring based), you will have to inject the entity manager manually. In that case, you could use something like this as base class:

public abstract class JpaBaseRolledBackTestCase {
    protected static EntityManagerFactory emf;

    protected EntityManager em;

    @BeforeClass
    public static void createEntityManagerFactory() {
        emf = Persistence.createEntityManagerFactory("PetstorePu");
    }

    @AfterClass
    public static void closeEntityManagerFactory() {
        emf.close();
    }

    @Before
    public void beginTransaction() {
        em = emf.createEntityManager();
        em.getTransaction().begin();
    }

    @After
    public void rollbackTransaction() {   
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }

        if (em.isOpen()) {
            em.close();
        }
    }
}

这篇关于如何在单元测试期间注入PersistenceContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆