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

GitHub Actions运行Maven测试时PostgreSQL连接被拒

问题定位

本地测试正常、GitHub Actions报localhost:5432连接拒绝,核心是三个配置问题:

  • 测试配置未指定数据源JDBC URL,Spring Boot默认兜底连接localhost:5432,本地能跑是因为你用的embedded PostgreSQL库在本地环境自动注入了连接参数,但CI环境下该自动注入逻辑因环境差异失效,没有替换默认连接地址。
  • 你配置了maven-surefire插件按类并行、10线程执行测试,Testcontainers启动的PostgreSQL容器默认是随机映射宿主端口,并行场景下容易出现容器未完全就绪、端口未完成映射就有测试类发起连接的情况。
  • GitHub Actions Runner环境的Docker默认权限配置和本地有差异,没有给Testcontainers组件配置适配参数,容易出现容器启动后端口映射异常的问题。
修复步骤
  • 统一测试数据源配置,移除冲突的embedded配置
    直接删除bootstrap-test.properties里所有embedded.postgresql.*配置,避免两套容器启动逻辑冲突。修改application-test.properties为如下内容,使用Testcontainers官方支持的自动感知JDBC URL,不需要手动配置端口、主机,框架会自动启动容器并注入正确的连接参数:
    spring.datasource.driver-class-name=org.postgresql.Driver
    spring.datasource.url=jdbc:tc:postgresql:latest:///test_db
    spring.datasource.username=postgres
    spring.datasource.password=root
    spring.jpa.hibernate.ddl-auto=update
    
  • 调整Maven Surefire插件配置,解决并行测试冲突
    修改pom.xml里的surefire插件配置,降低并行粒度,添加Testcontainers适配CI的系统参数:
    <plugin>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.22.2</version>
        <configuration>
            <parallel>methods</parallel>
            <threadCount>4</threadCount>
            <systemPropertyVariables>
                <testcontainers.reuse.enable>false</testcontainers.reuse.enable>
            </systemPropertyVariables>
        </configuration>
    </plugin>
    
  • 优化GitHub Actions工作流配置,提前拉取镜像避免超时
    调整工作流文件,在测试执行前提前拉取PostgreSQL镜像,避免测试启动时拉取镜像超时导致容器启动失败:
    jobs:
      build:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v3
          - name: Set up JDK 17
            uses: actions/setup-java@v3
            with:
              java-version: '17'
              distribution: 'temurin'
              cache: maven
          - name: Pre-pull test database image
            run: docker pull postgres:latest
          - name: Execute tests
            run: mvn test -B
    
验证方式

本地执行mvn test确认所有用例通过后提交代码,查看CI日志:

  • 能看到Testcontainers输出的PostgreSQL容器启动日志
  • 数据源连接地址不再是固定的localhost:5432,而是框架自动注入的带随机端口的映射地址
  • 所有测试用例正常执行,无连接拒绝报错

内容的提问来源于stack exchange,提问作者Emin Bilgic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:39:24