【问题标题】:Spring + JUnit + H2 + JPA : Is it possible to drop-create the database for every test?Spring + JUnit + H2 + JPA:是否可以为每个测试创建数据库?
【发布时间】:2014-02-10 09:04:58
【问题描述】:

为了保持 JUnit 测试之间的独立性,我需要在每次测试开始时创建数据库,并在每次测试结束时销毁它。

应通过执行存在于 SQL 文件中的 SQL 查询(本机插入查询...)在内存中创建数据库(H2 数据库)。

在属性文件中定义我的键值对并遵守 JPA 规范 (persistence.xml),如何使用注解/注入为每个 JUnit 测试创建删除数据库?

非常感谢!

【问题讨论】:

  • 我已经描述了与 Arquillian 合作的安排,但使用 JBoss 7.1.1 而不是 Spring 和 Hibernate 作为 JPA impl。如果你能在 Spring 中使用 Arquillian,请告诉我。

标签: spring jpa junit h2


【解决方案1】:

您应该能够使用 Spring 的嵌入式数据库配置来指定 H2 数据源(也显示为 here):

<jdbc:embedded-database id="dataSource" type="H2">
    <!-- Modify locations appropriately for your environment -->
    <jdbc:script location="classpath:db-schema.sql"/>
    <jdbc:script location="classpath:db-test-data.sql"/>
</jdbc:embedded-database>

这应该包含在您的特定于测试的testApplicationContext.xml 中,并带有适当的命名空间声明。

Spring 将在测试套件(测试类)开始时调出测试应用程序上下文时创建 H2 数据源。由于 Spring 在测试类的持续时间内缓存应用程序上下文,您可以使用 @DirtiesContext 注释测试类,以便为每个测试方法重新创建应用程序上下文并重新初始化数据源:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:/your/testApplicationContext.xml"})
@DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)
public class SomeDatabaseTest {

    @Autowired
    private SomeDao dao;

    // Test methods
}

有关 Spring 的嵌入式数据库功能的更多信息可以找到 here

【讨论】:

    【解决方案2】:

    您可能应该使用 JPA 或 Spring 功能,但只是为了完整性:

    在数据库端,H2支持running init scripts when opening the database如下:

    jdbc:h2:mem:test;INIT=runscript from '~/create.sql'
    

    jdbc:h2:mem:test;INIT=runscript from 'classpath:/com/acme/create.sql'
    

    当您关闭内存数据库时(如上面的示例),数据将被删除。或者您可以运行 SQL 语句 drop all objects

    【讨论】:

      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2015-11-20
        • 1970-01-01
        • 2020-12-25
        • 2018-08-24
        • 1970-01-01
        • 2013-07-13
        相关资源
        最近更新 更多