How to inject PersistenceContext during unit testing?

前端 未结 3 1543
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 14:55

This is my java class:

public class Finder {
  @PersistenceContext(unitName = \"abc\")
  EntityManager em;
  public boolean exists(int i) {
    return (this.em.f         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 15:24

    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();
            }
        }
    }
    

提交回复
热议问题