``` func TestFooerTableDriven(t *testing.T) { // Defining the columns of the table var tests = []struct { name string input int want string }{ // the table itself {"9 should be Foo", 9, "Foo"}, {"3 should be Foo", 3, "Foo"}, {"1 is not Foo", 1, "1"}, {"0 should be Foo", 0, "Foo"}, } // The execution loop for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ans := Fooer(tt.input) if ans != tt.want { t.Errorf("got %s, want %s", ans, tt.want) } }) } } ``` ``` 表驱动测试从定义输入结构开始。 这相当于定义表的列。 表的每一行都列出了待执行的测试用例。 定义表后,您可以编写执行循环。 执行循环会调用定义子测试的 t.Run()。 因此,表的每一行都定义了一个名为 `[NameOfTheFuction]/[NameOfTheSubTest]` 的子测试。 这种测试编写方式非常流行,也被视作在 Go 中编写单元测试的规范方式。 GoLand 可以为您生成这些测试模板。 您可以右键点击函数,转到 Generate | Test for function(生成 | 函数测试)。 查看 GoLand 文档了解更多详细信息。 您只需要添加测试用例: ```go
{“9 should be Foo”, args{9}, “Foo”},
{“3 should be Foo”, args{3}, “Foo”},
{“1 is not Foo”, args{1}, “1”},
{“0 should be Foo”, args{0}, “Foo”},