为了账号安全,请及时绑定邮箱和手机立即绑定

如何启动内存数据库来测试 JPA 实体?

如何启动内存数据库来测试 JPA 实体?

红颜莎娜 2023-09-06 15:52:07
因为我没有大量 JPA 经验,所以我想编写一个自动化测试来确保我的 JPA 实体正在检索我希望它们检索的记录。我的计划是为我的测试启动一个内存中的 H2 DB,并对其执行一些简单的 CRUD 操作,确保数据按我的预期返回。我不知道如何让 Spring Boot 创建内存数据库。这是我到目前为止所拥有的,但不起作用。这是创建我的 JPA 存储库的配置。这是正确的应用程序代码,目前正在与我实际的 Oracle DB 一起使用。@Configuration@EnableJpaRepositories("com.name.project.webservice.dao")@EntityScan("com.name.project.webservice.types")public class JpaRepositoriesConfig {    // Intentionally empty.}我将此配置导入到我的测试中。@RunWith(SpringRunner.class)@SpringBootTest(classes = {JpaRepositoriesConfig.class})public class JpaEntityTest {    @Test    public void test(){}}然后,我编写一个特定于测试的属性文件 ,src/test/resources/application.properties用测试的 H2 配置替换应用程序的 Oracle 配置。spring.datasource.driver-class-name=org.h2.Driverspring.datasource.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1最后,我将 H2 jar 添加到我的 pom.xml 中。这个 jar 的存在以及我的测试中的注释应该指示 Spring Boot 根据我的属性文件启动 H2 数据库。<dependency>    <groupId>com.h2database</groupId>    <artifactId>h2</artifactId>    <scope>test</scope></dependency>这个错误让我很惊讶。我认为Spring Boot应该自动给我一个entityManagerFactory;我的应用程序从不实例化一个entityManagerFactory bean,它工作得很好。因此,如果您不介意告诉我,我是否至少走在正确配置的正确轨道上?我错过了哪一步导致了这个错误?我需要手动声明entityManagerFactory吗?感谢您的帮助。编辑:这是我的应用程序属性文件的相关部分,而不是上面记录的测试属性文件。spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriverspring.datasource.url= <<database-url>>spring.datasource.tomcat.max-active=5spring.datasource.tomcat.initial-size=1spring.datasource.tomcat.max-wait=20000 spring.datasource.tomcat.max-idle=1
查看完整描述

2 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

我能够通过在我的测试类上使用以下注释将内存数据库添加到 Spring 上下文:


@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = { JpaRepositoriesConfig.class })

@DataJpaTest

当然,包括在我的 pom 中必要的依赖项:


<dependency>

    <groupId>com.h2database</groupId>

    <artifactId>h2</artifactId>

    <scope>test</scope>

</dependency>

如果我正在做的事情违反了任何最佳实践,请告诉我。


查看完整回答
反对 回复 2023-09-06
?
森栏

TA贡献1810条经验 获得超5个赞

我确实看到您正在维护单独的属性文件以进行测试,这意味着您正在使用测试属性创建数据源和实体管理器并加载 spring boot 原始应用程序上下文。所以你不需要任何额外的测试配置


@RunWith(SpringRunner.class)

@SpringBootTest

public class JpaEntityTest {


     @Test

     public void test(){}

}

您还可以使用配置文件来执行此操作,命名application.properties并application-test.properties使用@Profile和@ActiveProfile


@RunWith(SpringRunner.class)

@SpringBootTest

@ActiveProfile("test")

@Profile("test")

public class JpaEntityTest {


     @Test

     public void test(){}

}


查看完整回答
反对 回复 2023-09-06
  • 2 回答
  • 0 关注
  • 89 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信