Use Cases

使用 Claude Code 实现 API 测试自动化:QA 实战指南

使用 Claude Code 实现 API 测试自动化。QA 实战指南。包含实用代码示例。

使用 Claude Code 实践 API 测试自动化

要保证 API 质量,全面的测试不可或缺。借助 Claude Code,你可以从测试用例设计到 Mock 生成、CI 集成一站式自动化。

测试用例设计

REST API 的 CRUD 测试

> 使用 Vitest + supertest 为用户 API 创建 CRUD 测试。
> 覆盖正常、异常和边界值测试。
// tests/api/users.test.ts
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import request from 'supertest';
import { app } from '../../src/app';
import { resetDatabase, seedUsers } from '../helpers/db';

describe('Users API', () => {
  beforeEach(async () => {
    await resetDatabase();
    await seedUsers();
  });

  describe('GET /api/users', () => {
    it('能够获取用户列表', async () => {
      const res = await request(app)
        .get('/api/users')
        .expect(200);

      expect(res.body.data).toBeInstanceOf(Array);
      expect(res.body.data.length).toBeGreaterThan(0);
      expect(res.body.data[0]).toHaveProperty('id');
      expect(res.body.data[0]).toHaveProperty('name');
      expect(res.body.data[0]).not.toHaveProperty('password');
    });

    it('分页功能正常工作', async () => {
      const res = await request(app)
        .get('/api/users?page=1&limit=5')
        .expect(200);

      expect(res.body.data.length).toBeLessThanOrEqual(5);
      expect(res.body.meta).toHaveProperty('totalPages');
      expect(res.body.meta).toHaveProperty('currentPage', 1);
    });
  });

  describe('POST /api/users', () => {
    it('能够创建新用户', async () => {
      const newUser = {
        name: '测试用户',
        email: '[email protected]',
        password: 'SecurePass123!',
      };

      const res = await request(app)
        .post('/api/users')
        .send(newUser)
        .expect(201);

      expect(res.body.data.name).toBe(newUser.name);
      expect(res.body.data.email).toBe(newUser.email);
    });

    it('无效邮箱地址时返回 400', async () => {
      const res = await request(app)
        .post('/api/users')
        .send({ name: 'Test', email: 'invalid', password: 'Pass123!' })
        .expect(400);

      expect(res.body.errors).toBeDefined();
    });

    it('重复邮箱地址时返回 409', async () => {
      await request(app)
        .post('/api/users')
        .send({ name: 'User1', email: '[email protected]', password: 'Pass123!' });

      await request(app)
        .post('/api/users')
        .send({ name: 'User2', email: '[email protected]', password: 'Pass456!' })
        .expect(409);
    });
  });
});

Mock 和 Stub 的生成

外部 API 依赖的测试

> 使用 MSW 创建 Stripe 支付 API 的 Mock。
// tests/mocks/handlers.ts
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.post('https://api.stripe.com/v1/charges', () => {
    return HttpResponse.json({
      id: 'ch_test_123',
      amount: 1000,
      currency: 'jpy',
      status: 'succeeded',
    });
  }),

  http.post('https://api.stripe.com/v1/refunds', () => {
    return HttpResponse.json({
      id: 're_test_456',
      amount: 1000,
      status: 'succeeded',
    });
  }),
];

契约测试

验证 API 规范与实现一致性的契约测试也可以用 Claude Code 生成。可以构建将 OpenAPI Schema 与响应进行自动比对的测试。

性能测试

> 使用 k6 创建 API 负载测试脚本。
> 采用逐步增加负载的场景。
import http from 'k6/http';
import { check, sleep } from 'k6';

export const options = {
  stages: [
    { duration: '1m', target: 50 },
    { duration: '3m', target: 50 },
    { duration: '1m', target: 100 },
    { duration: '3m', target: 100 },
    { duration: '1m', target: 0 },
  ],
  thresholds: {
    http_req_duration: ['p(95)<500'],
    http_req_failed: ['rate<0.01'],
  },
};

总结

借助 Claude Code,你可以从 API 测试设计到实现、CI 集成一站式自动化。也建议参考测试策略指南CI/CD 流水线构建

API 测试的详细信息请参阅 Vitest 官方文档

#Claude Code #API testing #automation #testing #quality assurance