首页 > 文章列表 > Golang函数如何测试?

Golang函数如何测试?

测试 golang
351 2024-04-23

Go 函数测试指南:单元测试用于隔离测试函数行为。testify/assert 提供有用的断言工具,需要导入 github.com/stretchr/testify/assert。使用 assert.Equal(t, 预期值, 函数调用) 进行断言。使用 go test 命令运行测试。

Golang函数如何测试?

Go 函数测试

在编写 Go 程序时,单元测试至关重要,它允许我们验证函数是否按预期运行。本文将提供有关如何测试 Go 函数的分步指南,并附有实战案例。

单元测试

单元测试是在隔离环境中测试函数的行为,而不考虑其他代码。

使用 testify/assert

testify/assert 是一个流行的 Go 测试包,具有一组有用的断言工具。要安装它,请运行:

go get github.com/stretchr/testify/assert

要使用 assert,首先需要在单元测试文件中导入它:

import "github.com/stretchr/testify/assert"

现在,您可以编写测试用例,如下所示:

func TestAdd(t *testing.T) {
  // 断言 a+b 等于 c
  assert.Equal(t, 3, Add(1, 2))
}

使用 go test

要运行单元测试,请在命令行中使用 go test 命令:

go test

实战案例

考虑以下用于计算两个数字之和的简单函数:

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

为了测试此函数,我们可以使用以下测试用例:

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

  for _, tc := range testCases {
    actual := Add(tc.a, tc.b)
    assert.Equal(t, tc.expected, actual)
  }
}

在测试用例中,我们将多个测试集合到 testCases 片段中。每个测试用例指定了输入值 ab,以及预期的结果 expected

循环遍历每个测试用例,调用 Add 函数并使用 assert 断言结果与预期值相匹配。如果任何断言失败,则测试将失败。