使用 H2 数据库测试 JPA 的最佳方法?

Best way to test JPA with H2 database?

我需要使用 spring 和 Junit 通过 H2 数据库测试 JPA,我在网上找到了很多方法,但我不确定最好的方法。

非常感谢。

尝试为您的 Spring 应用程序创建一个测试配置文件,并在该配置文件中创建 H2 数据源并注入它。如果您的是 spring 引导项目,则可以使用 属性 文件(如 application-dev.properties 或 application-test.properties 来分析数据源。否则在不同的配置文件下创建不同的 bean 定义。默认情况下 Maven/Gradle 使用 profile=test 运行测试。

因此当运行 测试时,H2 数据库被拾取。内存数据库中的 H2 会更好,因为每次测试开始时它都可以 drop/create.

如果您正在寻找任何特定的 specification/measure 来决定好的方法,请在此处发表评论。

确实有几种配置 Spring/JPA 测试套件的方法,很难确定最佳方法。只要它们涵盖了下面提到的要点,您就可以自由使用它们中的任何一个,只需尝试一下,看看哪一个最适合您。

  • 确保管理 JPA 数据库配置的配置是外部化的。您可以通过指定不同的 spring 配置文件或覆盖 Spring PropertyConfigurer 来实现此目的。对于 Spring 引导项目,测试的基础 class 可能类似于下面的代码片段:


    @ContextConfiguration(initializers = ConfigFileApplicationContextInitializer.class, locations = "classpath:applicationContext-integrationtest.xml")
    @ActiveProfiles("integrationtest")
    @Ignore("An abstract base class for the tests")
    public abstract class AbstractIntegrationTest extends AbstractTransactionalJUnit4SpringContextTests {
    }
  • 确保控制数据源配置的属性在集成测试属性文件中被覆盖。主要的数据库特定属性是:

    • 数据库用户名(通常在 datasource/connection 池中设置)- sa
    • 数据库密码(通常在 datasource/connection 池上设置)-``
    • 数据库连接URL(通常设置在datasource/connection池上)-jdbc:h2:database/integrationtest
    • 数据库JDBC驱动程序class(通常设置在datasource/connection池上)-org.h2.Driver
    • 数据库方言(通常在 EntityManagerFactory JPA 提供程序特定配置上设置)- org.hibernate.dialect.H2Dialect

我正在使用这个库。我工作得非常好,而且大惊小怪。 https://github.com/mmnaseri/spring-data-mock