登录
首页 >  Golang >  Go教程

Golang测试基础:testing包使用详解

时间:2025-09-05 10:36:59 181浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《Golang单元测试基础:testing包使用教程》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

Go语言单元测试通过testing包实现,测试文件命名为xxx_test.go且与被测文件同包,测试函数以Test开头并接收*testing.T参数,使用t.Errorf或t.Fatalf报告错误,推荐采用表驱动测试方式并通过t.Run创建子测试以提高可维护性和可读性,运行go test命令执行测试并用-v参数查看详细结果,最终确保代码正确性。

如何编写基础Golang单元测试 使用testing包简单示例

编写 Go 语言的单元测试非常简单,标准库中的 testing 包提供了完整的支持。下面通过一个基础示例,展示如何为一个简单的函数编写单元测试。


1. 被测试函数示例

假设我们有一个计算两个整数之和的函数,放在 math.go 文件中:

// math.go
package main

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

2. 编写对应的测试文件

Go 的测试文件命名规则是:_test.go,且与被测文件在同一个包中。创建 math_test.go

// math_test.go
package main

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5

    if result != expected {
        t.Errorf("Add(2, 3) = %d; expected %d", result, expected)
    }
}

说明:

  • 测试函数名必须以 Test 开头,可选后接大写字母或单词(如 TestAdd, TestAddNegative)。
  • 参数 t *testing.T 是测试的上下文,用于记录错误、控制测试流程。
  • 使用 t.Errorf 报告错误,测试会标记为失败,但继续执行;t.Fatalf 会中断测试。

3. 运行测试

在项目目录下执行:

go test

输出应为:

PASS
ok      your-project-name    0.001s

如果想看更详细的信息,加上 -v 参数:

go test -v

输出类似:

=== RUN   TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok      your-project-name    0.001s

4. 添加更多测试用例(表驱动测试)

对于多个输入组合,推荐使用“表驱动测试”(table-driven test),更清晰、易维护:

// math_test.go
func TestAdd(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"positive numbers", 2, 3, 5},
        {"negative numbers", -2, -3, -5},
        {"mixed signs", -2, 3, 1},
        {"zero", 0, 0, 0},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            result := Add(tt.a, tt.b)
            if result != tt.expected {
                t.Errorf("got %d, want %d", result, tt.expected)
            }
        })
    }
}

说明:

  • 使用 t.Run 创建子测试,每个测试用例独立运行。
  • 输出中会显示每个子测试的名称,便于定位失败项。

运行结果示例:

=== RUN   TestAdd
=== RUN   TestAdd/positive_numbers
=== RUN   TestAdd/negative_numbers
=== RUN   TestAdd/mixed_signs
=== RUN   TestAdd/zero
--- PASS: TestAdd (0.00s)
    --- PASS: TestAdd/positive_numbers (0.00s)
    --- PASS: TestAdd/negative_numbers (0.00s)
    --- PASS: TestAdd/mixed_signs (0.00s)
    --- PASS: TestAdd/zero (0.00s)
PASS

小结

  • 测试文件命名:xxx_test.go
  • 测试函数:func TestXxx(t *testing.T)
  • 使用 t.Errort.Fatal 报告错误
  • 推荐使用表驱动测试处理多用例
  • t.Run 组织子测试,提升可读性

基本上就这些。Go 的测试机制简洁直接,配合 go test 命令即可快速验证代码正确性。

今天关于《Golang测试基础:testing包使用详解》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>