API测试 #

一、API测试概述 #

1.1 测试类型 #

类型 说明
功能测试 验证API功能
性能测试 测试响应时间
安全测试 验证安全性
集成测试 测试组件集成

二、功能测试 #

2.1 CRUD测试 #

go
package main

import (
    "bytes"
    "encoding/json"
    "net/http/httptest"
    "testing"
    
    "github.com/gofiber/fiber/v2"
    "github.com/stretchr/testify/assert"
)

func TestUserAPI(t *testing.T) {
    app := fiber.New()
    
    var users []map[string]interface{}
    
    app.Get("/users", func(c *fiber.Ctx) error {
        return c.JSON(users)
    })
    
    app.Post("/users", func(c *fiber.Ctx) error {
        var user map[string]interface{}
        c.BodyParser(&user)
        users = append(users, user)
        return c.Status(201).JSON(user)
    })
    
    app.Get("/users/:id", func(c *fiber.Ctx) error {
        id := c.Params("id")
        for _, u := range users {
            if u["id"] == id {
                return c.JSON(u)
            }
        }
        return c.Status(404).SendString("Not found")
    })
    
    t.Run("ListUsers", func(t *testing.T) {
        req := httptest.NewRequest("GET", "/users", nil)
        resp, _ := app.Test(req)
        assert.Equal(t, 200, resp.StatusCode)
    })
    
    t.Run("CreateUser", func(t *testing.T) {
        body, _ := json.Marshal(map[string]string{"id": "1", "name": "John"})
        req := httptest.NewRequest("POST", "/users", bytes.NewReader(body))
        req.Header.Set("Content-Type", "application/json")
        resp, _ := app.Test(req)
        assert.Equal(t, 201, resp.StatusCode)
    })
    
    t.Run("GetUser", func(t *testing.T) {
        req := httptest.NewRequest("GET", "/users/1", nil)
        resp, _ := app.Test(req)
        assert.Equal(t, 200, resp.StatusCode)
    })
}

三、集成测试 #

3.1 完整应用测试 #

go
func TestIntegration(t *testing.T) {
    // 设置测试数据库
    db := setupTestDB()
    defer db.Close()
    
    // 创建应用
    app := setupApp(db)
    
    // 测试完整流程
    t.Run("RegisterAndLogin", func(t *testing.T) {
        // 注册
        body := `{"username":"test","password":"password"}`
        req := httptest.NewRequest("POST", "/register", strings.NewReader(body))
        req.Header.Set("Content-Type", "application/json")
        resp, _ := app.Test(req)
        assert.Equal(t, 201, resp.StatusCode)
        
        // 登录
        req = httptest.NewRequest("POST", "/login", strings.NewReader(body))
        req.Header.Set("Content-Type", "application/json")
        resp, _ = app.Test(req)
        assert.Equal(t, 200, resp.StatusCode)
    })
}

四、性能测试 #

4.1 基准测试 #

go
func BenchmarkGetUsers(b *testing.B) {
    app := fiber.New()
    app.Get("/users", func(c *fiber.Ctx) error {
        return c.JSON([]string{"user1", "user2"})
    })
    
    b.ResetTimer()
    
    for i := 0; i < b.N; i++ {
        req := httptest.NewRequest("GET", "/users", nil)
        app.Test(req)
    }
}

五、总结 #

5.1 API测试要点 #

要点 说明
功能测试 验证API功能
集成测试 测试完整流程
性能测试 基准测试
安全测试 认证授权

5.2 下一步 #

现在你已经掌握了API测试,接下来让我们学习 Docker部署,了解容器化部署!

最后更新:2026-03-28