全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 2026-05-21 5 分钟 ✍️ juanwangdev

容器化测试环境

容器化测试环境可快速拉起完整依赖栈,下面介绍配置方法。

测试依赖栈

YAML
# docker-compose.test.yml
version: '3.8'

services:
  app:
    build: .
    environment:
      NODE_ENV: test
      DB_HOST: postgres
      REDIS_HOST: redis
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_healthy
    command: npm test

  postgres:
    image: postgres:15
    environment:
      POSTGRES_DB: testdb
      POSTGRES_PASSWORD: test_password
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 5

  redis:
    image: redis:7-alpine
    healthcheck:
      test: ["CMD", "redis-cli", "ping"]
      interval: 5s
      timeout: 3s
      retries: 5

运行测试

Bash
# 启动测试环境
docker compose -f docker-compose.test.yml up -d

# 查看测试输出
docker compose -f docker-compose.test.yml logs -f app

# 运行完成后清理
docker compose -f docker-compose.test.yml down -v

一次性测试

Bash
# 运行测试并自动清理
docker compose -f docker-compose.test.yml up --abort-on-container-exit

# 或
docker compose -f docker-compose.test.yml up --exit-code-from app

测试数据库初始化

YAML
services:
  postgres:
    image: postgres:15
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    environment:
      POSTGRES_DB: testdb
      POSTGRES_PASSWORD: test_password

init.sql

SQL
CREATE TABLE users (id SERIAL PRIMARY KEY, name VARCHAR(100));
INSERT INTO users (name) VALUES ('Test User');

CI/CD 集成

YAML
# GitHub Actions
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:15
        env:
          POSTGRES_PASSWORD: test_password
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5          

    steps:
      - uses: actions/checkout@v3
      - run: docker compose -f docker-compose.test.yml up --exit-code-from app

Mock 服务

YAML
services:
  mock-api:
    image: mockserver/mockserver
    ports:
      - "1080:1080"
    environment:
      MOCKSERVER_WATCH_INITIALIZATION_JSON: "true"
    volumes:
      - ./mockserver.json:/config/initializerJson.json

要点总结

  • Compose 定义测试依赖栈(DB、Redis、MQ 等)
  • 健康检查确保依赖就绪后再启动测试
  • --exit-code-from 返回测试容器退出码
  • 测试完成 down -v 清理数据卷
  • CI/CD 集成容器化测试,保证环境一致性
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 多环境配置管理
下一篇 → 自动化构建推送
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码