在测试用例之后回滚种子数据插入



我正在使用Kotlin和Ktor开发一个JPA应用程序,并使用Hibernate作为ORM。

我的测试数据库是h2,hibernate.hbm2ddl.auto设置为创建,以便在SessionFactory关闭后清理所有数据。

但是现在要有一个干净的数据库状态,我需要在每个测试用例之后重新创建 EntityManagerFactory,这使得测试非常非常慢,因此我正在寻找一种不同的方法来执行此操作。

我已经读过关于事务注释的文章,但显然这只能在 Spring 框架中工作。

有没有人知道如何在测试用例运行后回滚来自 before 方法的插入?

下面是一个示例:

class ChampionDaoTests {
    var chmpDao : IChampionDao? = null
    val chmp1 = TestHelper.generateChampionObj()
    val chmp2 = TestHelper.generateChampionObj()
    @Before
    fun before() {
        // Should be rolled back after each Test case
        chmpDao = ChampionDao(TestHelper.getEntityManager())
        (this.chmpDao as ChampionDao).saveChampion(chmp1)
        (this.chmpDao as ChampionDao).saveChampion(chmp2)
    }
    @Test
    fun testFindAllMethod() {
        val chmps : List<Champion> = this.chmpDao!!.findAllChampions()
        assertTrue { chmps.size == 2 }
    }
    @Test
    fun testFindChampionMethod() {
        val chmp = this.chmpDao!!.findChampionById(chmp1.chmpid!!)
        assertNotNull(chmp)
        if (chmp != null) {
            assertTrue { chmp.equals(chmp1) }
        }
    }
    @Test
    fun testFindChampionMethodWrongParam() {
        val chmp = this.chmpDao!!.findChampionById(-1)
        assertNull(chmp)
    }
}

您可以使用 Before 和 After 方法创建一个基测试类,该方法控制每个测试方法的事务:

public abstract class BaseTestWithEntityManager {
    protected static EntityManagerFactory emf;
    protected static EntityManager em;
    protected EntityTransaction transaction;
    @Before
    public void beforeSuper() {
        transaction = em.getTransaction();
        transaction.begin();
    }
    @After
    public void afterSuper() {
        em.flush();
        if (transaction.isActive()) {
            transaction.rollback();
        }
    }
    @BeforeClass
    public static void beforeClass() {
        emf = Persistence.createEntityManagerFactory("store");
        em = emf.createEntityManager();
    }
    @AfterClass
    public static void afterClass() {
        if (em.isOpen()) {
            em.close();
        }
        if (emf.isOpen()) {
            emf.close();
        }
    }
}

最新更新