我正在使用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
我在这里想念什么?
答案 0 :(得分:0)
您需要做的就是在test
范围内包括H2数据库依赖项。
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
只要您使用Spring Boot,framwork就会自动在类路径的test
范围内检测到此依赖关系,并使用默认设置(与您提供的设置相匹配)启动测试阶段的数据库必填。
我想您使用的是jUnit 5,因此对测试类使用以下注释:
@SpringBootTest
@ExtendWith(MockitoExtension.class)
public class MyTest() {
}
答案 1 :(得分:0)
我猜想当您进行集成测试时,需要在上下文中加载数据库配置。希望这些注释对您的情况有用
@DataJpaTest // required
@ActiveProfiles("test") //optional: setting the profile you want to test
@ContextConfiguration(classes = {DatabaseConfig.class}) // load the configurations
参考链接: