Golang教程单元测试和基准测试

如何在Golang中编写有效的单元测试?我目前对testing包的基础用法比较熟悉,但想了解更高级的测试技巧,比如表格驱动测试和mock的使用场景。另外,基准测试在实际项目中应该如何应用?我看文档中可以通过go test -bench运行基准测试,但不太确定如何解读结果以及如何优化性能。能否分享一些单元测试和基准测试的最佳实践案例?

3 回复

Go语言内置了对单元测试和基准测试的支持。

单元测试

  1. 在源文件旁边创建同名的_test.go文件。例如,hello.go的单元测试写在hello_test.go中。
  2. 使用go test命令运行测试。
  3. 定义测试函数,命名格式为TestXxx(*testing.T)。例如:
    func TestAdd(t *testing.T) {
        result := Add(1, 2)
        if result != 3 {
            t.Errorf("Add(1,2) failed, want 3, got %d", result)
        }
    }
    
  4. 可选地使用表驱动测试来管理多个测试用例。

基准测试

  1. 定义基准测试函数,命名格式为BenchmarkXxx(*testing.B)
  2. 在函数中循环执行被测代码多次以获取性能数据。例如:
    func BenchmarkAdd(b *testing.B) {
        for i := 0; i < b.N; i++ {
            Add(1, 2)
        }
    }
    
  3. 使用go test -bench=.运行基准测试。
  4. Go会输出每次操作的耗时、内存分配等信息。

这两者帮助开发者确保代码质量和性能优化。记得在编写测试时尽量覆盖边界条件和异常情况。

更多关于Golang教程单元测试和基准测试的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Go语言内置了强大的单元测试和基准测试支持。

单元测试:以_test.go结尾的文件中编写。例如,假设有一个math包:

// math/math.go
package math

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

对应的单元测试:

// math/math_test.go
package math

import "testing"

func TestAdd(t *testing.T) {
    res := Add(2, 3)
    if res != 5 {
        t.Errorf("Expected 5, got %d", res)
    }
}

运行go test ./...即可执行所有测试。

基准测试:使用Benchmark开头的函数。继续上面的例子:

// math/math_bench_test.go
package math

import "testing"

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

运行go test -bench=.即可执行基准测试。通过这些工具,可以轻松验证代码的正确性和性能。

Golang单元测试和基准测试教程

单元测试

在Go中,单元测试是通过testing包实现的。测试文件需要以_test.go结尾,测试函数必须以Test开头。

基本示例

假设我们有一个math.go文件:

package math

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

对应的测试文件math_test.go

package math

import "testing"

func TestAdd(t *testing.T) {
    tests := []struct {
        a, b, expected int
    }{
        {1, 2, 3},
        {0, 0, 0},
        {-1, -1, -2},
    }

    for _, test := range tests {
        result := Add(test.a, test.b)
        if result != test.expected {
            t.Errorf("Add(%d, %d) = %d; expected %d", test.a, test.b, result, test.expected)
        }
    }
}

运行测试:

go test

基准测试

基准测试用于测量代码性能,函数以Benchmark开头。

基准测试示例

math_test.go中添加基准测试:

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

运行基准测试:

go test -bench=.

表格驱动测试

Go推荐使用表格驱动测试(如上例所示),它有以下优点:

  1. 测试用例集中在一处
  2. 容易添加新测试用例
  3. 测试逻辑清晰

常用命令

  • go test:运行当前目录下的测试
  • go test -v:显示详细测试信息
  • go test -run TestName:运行特定测试
  • go test -bench=.:运行所有基准测试
  • go test -cover:查看测试覆盖率

测试覆盖率

生成覆盖率报告:

go test -coverprofile=coverage.out
go tool cover -html=coverage.out
回到顶部