使用 Testify 工具包
github.com/stretchr/testify 包是一个广泛使用的 Go 单元测试库。 它提供了一组工具,例如断言、mock 和测试套件,让在 Go 中编写测试更加容易。 使用 Testify,您可以像常规测试函数一样运行测试套件和方法。 有关该工具包的更多信息,请参阅 GitHub 上的 Testify 说明。
在本教程中,您将为 main.go 文件中的以下应用生成并使用测试:
package math
// Add returns the sum of two integers.
func Add(a, b int) int {
return a + b
}
为包生成测试
打开您希望为其生成测试的 Go 文件。
在主菜单中,点击 。
在 生成 弹出窗口中,选择 包测试。
GoLand 会创建一个包含表格测试模板的 _test.go 文件。

修改生成的测试,使其使用 testify 工具包。请参考以下代码片段。 请参考以下代码片段。
package math
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestAdd(t *testing.T) {
type args struct {
a int
b int
}
tests := []struct {
name string
args args
want int
}{
{"add positives", args{1, 2}, 3},
{"add negatives", args{-1, -2}, -3},
{"add positive and negative", args{-1, 1}, 1},
{"add zeros", args{0, 0}, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.args.a, tt.args.b)
assert.Equal(t, tt.want, result, "they should be equal")
})
}
}
GoLand 已自动添加以下导入声明: "github.com/stretchr/testify/assert"。
同步缺失的依赖项
点击缺失的导入声明。
按下 Alt+Enter ,然后选择 修复缺失的依赖项。

使用 Testify 运行测试
比较期望值和实际值
您可以比较失败断言测试的期望值和实际值。
You can compare expected and actual values for failed assertion tests. 若要查看差异,请点击 单击查看差异 链接,然后在 运行 面板中查看。

右键点击失败的测试,然后选择 查看差异。 或者,按 Ctrl+D。

最后修改日期: 2025年 9月 26日
