Skip to content

Day 16 - 单元测试 ​

测试文件 ​

go
// math_test.go
package main

import "testing"

// 测试函数必须以Test开头
func TestAdd(t *testing.T) {
    result := add(1, 2)
    if result != 3 {
        t.Errorf("expected 3, got %d", result)
    }
}

运行测试 ​

bash
go test ./...
go test -v
go test -cover

子测试 ​

go
func TestMath(t *testing.T) {
    t.Run("add", func(t *testing.T) {
        // ...
    })
    t.Run("sub", func(t *testing.T) {
        // ...
    })
}

基准测试 ​

go
func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        add(1, 2)
    }
}

📅 学习进度 ​

Day主题状态
01-15基础✅
16单元测试✅
17Web框架-Gin⬜

本文为Go 30天学习计划第16天内容 ​

📚 导航 ​

| ← Day 15 - 上一章 | Day 17 - 下一章 →

最后更新: