侧边栏壁纸
博主头像
colo

欲买桂花同载酒

  • 累计撰写 1823 篇文章
  • 累计收到 0 条评论

编写一个简单的Go测试函数

2025-12-11 / 0 评论 / 4 阅读

题目

编写一个简单的Go测试函数

信息

  • 类型:问答
  • 难度:⭐

考点

Go测试基础,测试函数命名,测试断言

快速回答

在Go中编写测试需要:

  • 创建_test.go后缀的文件
  • 导入testing
  • 测试函数命名格式:TestXxx(t *testing.T)
  • 使用t.Errort.Fatal报告失败
  • 运行测试:go test
## 解析

1. 原理说明

Go内置的testing包提供轻量级测试框架:

  • 测试文件必须命名为*_test.go
  • 测试函数必须是TestXxx格式(Xxx首字母大写)
  • 测试函数参数固定为t *testing.T
  • 通过t的方法控制测试流程和报告

2. 代码示例

被测代码(math.go):

package math

func Add(a, b int) int {
    return a + b
}

测试代码(math_test.go):

package math

import "testing"

func TestAdd_PositiveNumbers(t *testing.T) {
    result := Add(2, 3)
    expected := 5
    if result != expected {
        t.Errorf("预期 %d, 实际 %d", expected, result)
    }
}

func TestAdd_NegativeNumbers(t *testing.T) {
    if Add(-1, -1) != -2 {
        t.Fatal("负数加法失败") // 立即终止当前测试
    }
}

3. 最佳实践

  • 命名规范Test[功能]_[场景](如TestAdd_Overflow
  • 错误报告
    • t.Error:报告失败但继续执行
    • t.Fatal:严重错误时立即终止
  • 表格驱动测试:推荐使用循环测试多组数据

4. 常见错误

  • ❌ 测试函数名不以Test开头
  • ❌ 忘记导入testing
  • ❌ 测试函数签名错误(如缺少t *testing.T
  • ❌ 在测试函数中使用panic代替错误报告

5. 运行与输出

执行测试:

go test -v  # -v 显示详细输出

成功输出:

=== RUN   TestAdd_PositiveNumbers
--- PASS: TestAdd_PositiveNumbers (0.00s)
=== RUN   TestAdd_NegativeNumbers
--- PASS: TestAdd_NegativeNumbers (0.00s)
PASS

失败输出(示例):

=== RUN   TestAdd_PositiveNumbers
    math_test.go:10: 预期 5, 实际 6
--- FAIL: TestAdd_PositiveNumbers (0.00s)

6. 扩展知识

  • 子测试:使用t.Run()创建嵌套测试
  • 覆盖率go test -cover查看测试覆盖率
  • 基准测试BenchmarkXxx(b *testing.B)函数