用于持久性和单元测试的通用DAO

时间:2013-10-17 20:42:32

标签: java hibernate unit-testing derby

这是我的BaseDAOImpl:

public class BaseDAOImpl implements GenericDAOI {
    protected Class entityClass;

    protected EntityManager entityManager;

    public BaseDAOImpl(Class entityClass,EntityManager entityManager){
        this.entityClass=entityClass;
        this.entityManager = entityManager;
    }

    public <ENTITY> ENTITY persist(ENTITY entity){
       EntityTransaction t=entityManager.getTransaction();
       t.begin();
       entityManager.persist(entity);
       t.commit();
       return entity;
     }

   public <ENTITY> ENTITY update(ENTITY entity){
       EntityTransaction t = entityManager.getTransaction();
       t.begin();
       ENTITY r = entityManager.merge(entity);
       t.commit();
       return r;
    }
   .... and so
}

我正在尝试对它进行单元测试:

public class BaseDAOImplTest {

    private EntityManagerFactory emFactory;
    private EntityManager em;
    private static Logger logger = Logger.getLogger(BaseDAOImplTest.class
            .getName());

    @Before
    public void setUp() throws SQLException, ClassNotFoundException {

        logger.info("Starting in-memory database for unit tests");

        try {

            //Creating testDB database
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            DriverManager.getConnection("jdbc:derby:memory:TestingDB;create=true");
            logger.info("Building JPA EntityManager for unit tests");

            //Creating Entity Manager
            emFactory = Persistence.createEntityManagerFactory("TestingDB");
            em = emFactory.createEntityManager();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
        }
    }

    @Test
    public void testPersistExcursion() {
        BaseDAOImpl baseDao = new BaseDAOImpl(Excursion.class, em);

        Calendar c = Calendar.getInstance();
        c.set(2013, 8, 24);
        Excursion ex1 = new Excursion(c.getTime(), 10, "Simple excursion 1", "New York", 35);
        ex1 = baseDao.persist(ex1);

        assertEquals(baseDao.findById(ex1.getId()), ex1);
    }

    @Test
    public void testUpdateExcursion() {
        BaseDAOImpl baseDao = new BaseDAOImpl(Excursion.class, em);

        Calendar c = Calendar.getInstance();
        c.set(2013, 8, 24);
        Excursion ex1 = new Excursion(c.getTime(), 10, "Simple excursion 1", "New York", 35);
        ex1 = baseDao.persist(ex1);
        ex1.setDestination("Prague");
        assertEquals(baseDao.update(ex1), ex1);
    }
}

只有坚持的第一次测试是可以的。但是第二次测试有问题。我在提交交易时遇到错误。那有什么不对?感谢

0 个答案:

没有答案