【问题标题】:SpringBootTest: Unable to find table in h2 databaseSpringBootTest:无法在 h2 数据库中找到表
【发布时间】:2021-04-12 18:31:13
【问题描述】:

我正在使用 h2 数据库对 JPA 存储库进行单元测试。

我在单元测试类中添加了以下注释:

@ExtendWith(SpringExtension.class)
@SpringBootTest

在测试中,我只是在 JPA 存储库中调用默认保存方法。

实体用注释定义为:

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Table(name = "coverage")

在 src/test/resources 中,我已经定义了 application.properties 的详细信息:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:db;
spring.datasource.username=sa
spring.datasource.password=sa
spring.datasource.platform=h2
spring.jpa.properties.hibernate.dialect= org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
spring.h2.console.enabled=true

我希望 SpringBootTest 能够读取我的实体类并在 h2 数据库中创建表。但我得到错误:

Caused by: org.postgresql.util.PSQLException: ERROR: relation "coverage" does not exist

我在这里错过了什么?

【问题讨论】:

  • 您在测试类上缺少@DataJpaTest 注释
  • 添加导致错误:java.lang.IllegalStateException:配置错误:发现测试类[com.here.had.webapps.repository.CoverageRepositoryTest]的@BootstrapWith的多个声明:[@org.springframework .test.context.BootstrapWith(value=org.springframework.boot.test.context.SpringBootTestContextBootstrapper), @org.springframework.test.context.BootstrapWith(value=org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTestContextBootstrapper )]
  • 尝试删除 @SpringBootTest 然后应该可以工作。我假设您想对存储库进行集成测试。我对吗?编辑:你能确认现在是否工作吗?
  • 是的,基本上它是一个集成测试。

标签: spring-boot h2 junit5


【解决方案1】:

您只需在 test 范围内包含 H2 数据库依赖项。

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

只要您使用 Spring Boot,框架就会自动在类路径上的 test 范围内检测此依赖关系,并使用默认设置(与您提供的相同)启动测试阶段的数据库,无需额外配置。

我假设您使用的是 jUnit 5,因此将这些注释用于测试类:

@SpringBootTest
@ExtendWith(MockitoExtension.class)
public class MyTest() {

}

【讨论】:

    【解决方案2】:

    我猜当您进行集成测试时,您需要在上下文中加载数据库配置。希望这些注释对您的情况有用

    @DataJpaTest // required
    @ActiveProfiles("test") //optional: setting the profile you want to test
    @ContextConfiguration(classes = {DatabaseConfig.class}) // load the configurations
    

    参考链接:

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 1970-01-01
      • 2020-08-12
      • 2018-06-02
      • 2019-01-14
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多