'JUnit and EntityTransaction

My base class

public abstract class JPABaseIT {

    protected static EntityManagerFactory emf;
    protected static EntityManager em;
    protected static EntityTransaction tx;

    protected JPABaseIT() {
        emf = Persistence.createEntityManagerFactory(getPersistenceUnit());
        em = emf.createEntityManager();
        tx = em.getTransaction();
    }

    protected abstract String getPersistenceUnit();

    protected abstract String getCleanQuery();

    @Before
    public void initTx(){
        tx.begin();
        em.createNativeQuery(getCleanQuery()).executeUpdate();
        tx.commit();
        tx.begin();
    }

    @After
    public void endTx() {
        if(tx != null && tx.isActive()) {
            if(!tx.getRollbackOnly()) {
                tx.commit();
            } else {
                tx.rollback();
            }
        }
    }

    @AfterClass
    public static void tearDownEM() {
        if (em != null) {
            em.clear();
            if (em.isOpen()) {
                em.close();
            }
            if (emf.isOpen()) {
                emf.close();
            }
        }
    }
}

My test (without building a context, using EM directly)

public class FooBeanIT extends JPABaseIT {

    protected FooBean service;


    public FooBeanIT() {
        service = new FooBean();
        service.setEntityManager(em);
    }

    @Override
    protected String getPersistenceUnit() {
        return "foo-TEST";
    }

    @Override
    protected String getCleanQuery() {
        return "TRUNCATE TABLE FOO;";
    }

    
    @Test
    public void updateFoo_test() {

        service.addFoo();   // -> em.persist()
        service.updateFooStatus(); // -> em.createNamedQuery().executeUpdate()
        Foo actual = service.getFooById();  // -> em.find()

    }

}

actual is returned but is not updated. I've tried to do tx.commit(); tx.begin(); after the update but is like being ignored. How should I get my entity updated in this kind of tests with multiple operations?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source