温馨提示×

在GitLab上如何实现自动化测试

小樊
47
2025-11-22 22:13:39
栏目: 编程语言

在 GitLab 上实现自动化测试

一 核心思路与前置准备

  • 使用 GitLab CI/CD:在代码仓库根目录放置 .gitlab-ci.yml,定义 stages(如 build、test)与 jobs,由 GitLab Runner 执行,实现提交即触发测试。Runner 可在 Linux/Debian/Ubuntu 等环境安装,并注册到你的 GitLab 实例(需要 URL注册令牌)。也可采用 Docker 镜像运行作业,保证环境一致性。触发时机可配置为 push、merge request 等事件。

二 最小可用流水线示例

  • 示例一 Node.js + Jest(生成 JUnit 报告)
stages:
  - test

variables:
  NODE_VERSION: "18"

test:
  stage: test
  image: node:$NODE_VERSION
  script:
    - npm ci
    - npm test -- --ci --reporters=jest-junit
  artifacts:
    when: always
    reports:
      junit: reports/junit.xml
    paths:
      - reports/
  • 示例二 Java + Maven(生成 Surefire 报告)
stages:
  - test

test:
  stage: test
  image: maven:3.9-openjdk-17
  script:
    - mvn test
  artifacts:
    when: always
    reports:
      junit: target/surefire-reports/TEST-*.xml

要点:通过 artifacts.reports.junit 指定测试结果文件路径,GitLab 会在 Pipelines/Jobs 页面展示测试报告与失败用例。

三 常见测试类型与配置要点

  • 单元测试:如 Jest/Mocha/JUnit,使用上述 JUnit 报告即可在界面直观查看通过率与失败详情。
  • 端到端 UI 测试:如 Playwright,在 CI 中安装浏览器并运行测试。
e2e:
  stage: test
  image: mcr.microsoft.com/playwright:v1.44.0-jammy
  script:
    - npm ci
    - npx playwright install --with-deps
    - npx playwright test --reporter=junit
  artifacts:
    when: always
    reports:
      junit: reports/e2e-junit.xml
    paths:
      - playwright-report/
  • 并行与缓存:按模块拆分作业并使用 parallel 提升速度;对 node_modulesMaven 本地仓库 等启用缓存减少安装耗时。
  • 触发与分支策略:用 only/exceptrules 控制哪些分支/事件触发哪些作业,例如仅 main 分支运行部署相关任务。

四 查看结果与质量门禁

  • 查看结果:在项目的 CI/CD → Pipelines → Jobs 查看作业日志;在 Tests 标签查看 JUnit 报告(通过率、失败用例、堆栈)。
  • 质量门禁:结合 rulesallow_failure: false 让关键测试失败阻断合并;使用 artifacts:when: always 确保即使失败也归档日志与报告,便于排查。

五 排错与最佳实践

  • Runner 连通性:确认 Runner 已 注册 到正确 GitLab 实例 URLtoken,且状态为 active;必要时为不同项目配置 tags 以匹配合适 Runner。
  • 环境一致性:优先使用 Docker 镜像 运行测试,减少“本机能跑、CI 失败”的环境差异。
  • 依赖与缓存:合理使用 cache/restore_cache 加速依赖安装;区分 缓存产物(报告需上传为 artifacts)。
  • 报告路径:确保测试框架输出到 JUnit XML 的路径与 artifacts.reports.junit 一致;失败作业也要上传以便定位。

0