Spring + JUnit + H2 + JPA : Is it possible to drop-create the database for every test?

标签 spring jpa junit h2

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

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

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

十分感谢!

最佳答案

您应该能够使用 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

关于Spring + JUnit + H2 + JPA : Is it possible to drop-create the database for every test?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21246802/

相关文章:

java - 是否可以在 Eclipse 中获取 JUnit 中的文本?

java - 通过创建线程池在运行 JUnit 测试脚本时在线程之间添加延迟

java - Spring:注解驱动的事务管理器

java - 堆栈溢出错误: null in both side relationship

jpa - 如何识别@PreUpdate 中的 EJB 实体属性更改?

java - 在 hibernate jpa OneToOne 关系中的 db 表上添加了额外的列

java - 如何在junit中编写字符串数组输入的测试用例?(junit新手)

spring - spring boot - redis键分隔符

java - 使用 UUID 作为主键时,Hibernate 得到错误的 ID 值

java - 通过 REST 的 Spring JPA