You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Spock+Testcontainers测试时JpaRepository注入为null问题求助

Spock + Testcontainers 测试中JpaRepository注入为null的解决方案

你的测试类未正确配置Spring测试上下文,导致@Autowired无法生效,以下是具体修复步骤:

关键问题分析

Spock的Spring集成需要显式启动Spring容器才能处理依赖注入,你的测试类仅添加了@Testcontainers,缺少Spring测试上下文初始化的注解,因此PersonRepository无法被注入。

修复步骤

1. 添加Spring测试注解

给测试类添加@SpringBootTest(Spring Boot项目)或@ContextConfiguration,用于启动Spring测试上下文。同时给Testcontainers容器实例添加@Container注解,让框架管理容器生命周期。

2. 动态注入数据库配置

通过@DynamicPropertySource静态方法,将Testcontainers容器的连接参数动态覆盖到Spring配置中,确保JPA能连接到测试容器。

3. 修正断言逻辑

personRepository.findAll()返回的是集合对象,断言应判断集合大小而非直接和0比较。

修复后的完整代码

@SpringBootTest
@Testcontainers
class PostgresTestContainer extends Specification {

    @Autowired
    private PersonRepository personRepository

    @Shared
    @Container
    PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("postgres:12-alpine")
            .withDatabaseName("test")
            .withUsername("test")
            .withPassword("test")

    @DynamicPropertySource
    static void configureDatabaseProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl)
        registry.add("spring.datasource.username", postgreSQLContainer::getUsername)
        registry.add("spring.datasource.password", postgreSQLContainer::getPassword)
    }

    def "waits until postgres accepts jdbc connections"() {
        when: "querying the database"
        def response = personRepository.findAll()

        then: "result is returned"
        response.size() == 0
    }
}

确认依赖配置

确保pom.xml中包含正确的依赖版本(版本号需与你的Spring/Spring Boot版本兼容):

<dependency>
    <groupId>org.spockframework</groupId>
    <artifactId>spock-spring</artifactId>
    <version>2.3-groovy-4.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>postgresql</artifactId>
    <version>1.19.0</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>spock</artifactId>
    <version>1.19.0</version>
    <scope>test</scope>
</dependency>

内容的提问来源于stack exchange,提问作者Guilherme de Mira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 03:55:17