# 使用 Testify 工具包

> For the complete documentation index, see [llms.txt](https://www.jetbrains.com/zh-cn/help/idea/llms.txt).

这个  `github.com/stretchr/testify` 包是一个最受欢迎的的 Go 库，用于编写单元测试。 它提供了一组工具，如断言、模拟和套件，使编写 Go 测试更容易。 使用 Testify，您可以将套件和方法运行为常规测试函数。 有关此工具包的更多信息，请参阅 [GitHub 上 Testify](https://github.com/stretchr/testify) 的描述。

在本教程中，我们将在  `main.go`  文件中为以下应用程序生成和使用测试：

```GO
package math

// Add returns the sum of two integers.
func Add(a, b int) int {
	return a + b
}
    
```

Procedure: 为 package 生成测试

1. 打开要为其生成测试的 Go 文件。

2. 在主菜单中，点击  `代码 | 生成` 。

3. 在   生成  弹出窗口中，选择   包的测试  。

IntelliJ IDEA 创建了一个包含表格测试模板的  `_test.go`  文件。

请修改生成的测试以使用 testify 工具包。 请考虑以下测试代码片段。

```GO
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")
    })
  }
}
    
```

IntelliJ IDEA 已自动添加以下导入声明：  `"github.com/stretchr/testify/assert"` 。

Procedure: 同步缺失的依赖项

1. 点击缺失的 import 声明。

2. 按 `Alt+Enter` (Windows), `⌥ ⏎` (macOS), `⌥ ⏎` (IntelliJ IDEA Classic (macOS)), `⌥ ⏎` (macOS System Shortcuts), `Alt+Enter` (XWin), `Alt+Enter` (GNOME), `Alt+Enter` (KDE), `Alt+Enter` (Emacs), `Alt+Enter` (Sublime Text), `⌥ ⏎` (Sublime Text (macOS)), `Alt+Enter` (Visual Studio), `⌥ ⏎` (Visual Studio (macOS)), `Alt+Enter` (NetBeans), `Ctrl+1` (Eclipse), `⌘ 1` (Eclipse (macOS))并选择   修复缺失的依赖项  。

Procedure: 使用 testify 运行测试

* 点击   运行测试   图标 ![运行测试图标](https://resources.jetbrains.com/help/img/idea/2026.3/app.actions.execute.svg) 然后选择   运行<configuration>  。

您还可以根据需要运行单个表格测试。

![使用 Testify 运行测试](https://resources.jetbrains.com/help/img/idea/2026.3/go_run_testify.png)

Procedure: 比较预期值和实际值

对于断言失败的测试，您可以比较预期值和实际值。

* 对于断言失败的测试，您可以比较预期值和实际值。 要查看差异，请点击   点击查看差异  链接，位于   运行  窗格中。

![比较预期值和实际值](https://resources.jetbrains.com/help/img/idea/2026.3/go_compare_expected_actual_results.png)

* 右键点击失败的测试并选择   查看差异  。 或者按 `Ctrl+D` (Windows), `⌘ D` (macOS), `⌘ D` (IntelliJ IDEA Classic (macOS)), `⌘ D` (macOS System Shortcuts), `Ctrl+D` (XWin), `Ctrl+D` (GNOME), `Ctrl+D` (KDE), `Ctrl+D` (Emacs), `Ctrl+D` (Sublime Text), `⌘ D` (Sublime Text (macOS)), `Ctrl+D` (Visual Studio), `⌘ D` (Visual Studio (macOS)), `Ctrl+D` (NetBeans), `Ctrl+D` (Eclipse), `⌘ D` (Eclipse (macOS))。

![比较预期值和实际值](https://resources.jetbrains.com/help/img/idea/2026.3/go_compare_expected_actual_results_context_menu.png)

