Linux上落地GitLab自动化测试的标准流程
关键配置与示例
典型目录结构与核心要素:定义 stages(如 build → test → deploy),在 jobs 中使用 image 指定运行环境,script 编写测试命令,使用 artifacts.reports.junit 上传 JUnit XML 报告,使用 cache 缓存依赖(如 node_modules/、Maven 本地仓库),通过 rules 或 only/except 精准控制触发条件,敏感信息放入 CI/CD Variables 并以 $VAR 引用。
示例一 Java Maven 单元测试(JUnit)
stages:
- test
unit_tests:
stage: test
image: maven:3.8-openjdk-11
script:
- mvn test
artifacts:
reports:
junit: target/surefire-reports/*.xml
paths:
- target/
expire_in: 1 week
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- ~/.m2/repository
要点:使用官方 maven 镜像保证环境一致性;JUnit 报告自动解析到合并请求与流水线视图。
示例二 Node.js + Jest
stages:
- test
test:
stage: test
image: node:18
script:
- npm ci
- npm test -- --ci
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- node_modules
要点:使用 npm ci 加速且可复现依赖;将覆盖率与测试结果输出到控制台,便于 GitLab 日志与报告聚合。
示例三 Python + Playwright 端到端测试
stages:
- test
e2e_tests:
stage: test
image: mcr.microsoft.com/playwright/python:stable
script:
- pip install -r requirements.txt
- playwright install --with-deps
- pytest --headless --junitxml=report.xml
artifacts:
reports:
junit: report.xml
paths:
- playwright-report/
expire_in: 1 week
要点:使用官方 Playwright 镜像(已内置浏览器与驱动);无头模式运行并将 JUnit 报告与 HTML 报告归档。
效率优化与质量门禁
常见问题与排查要点