
go 单元测试函数必须接收 *testing.t 类型参数,而非 *testing.t;同时 testing 包仅在测试文件中导入才有效,主逻辑文件中不应引入。
go 单元测试函数必须接收 *testing.t 类型参数,而非 *testing.t;同时 testing 包仅在测试文件中导入才有效,主逻辑文件中不应引入。
在 Go 中,编写单元测试需严格遵循约定:测试函数名必须以 Test 开头,且唯一参数类型必须为 *testing.T(注意大小写和包名——是 testing.T,不是 Testing.T 或其他变体)。你遇到的两个编译错误正是源于此:
- imported and not used: "testing":说明你在 HelloTemplate.go(非 _test.go 文件)中错误导入了 "testing" 包,而该文件并非测试文件,无需也不允许依赖测试专用包;
- undefined: Testing in Testing.T:因拼写错误(首字母大写)及包名误用,Go 无法识别 Testing.T —— 正确类型是 testing.T,其中 testing 是小写标准库包名。
✅ 正确做法如下:
仅在测试文件中导入 testing
将 import "testing" 移至 HelloTemplate_test.go,并删除 HelloTemplate.go 中的该导入。修正测试函数签名
使用 testing.T,而非 Testing.T 或其他形式:
// HelloTemplate_test.go
package templateprint
import (
"os"
"testing" // ✅ 正确:仅在 _test.go 中导入
"text/template"
)
type Inventory struct {
Material string
Count uint
}
func TestRunTempl(t *testing.T) { // ✅ 正确:*testing.T,小写 testing
sweaters := Inventory{"wool", 17}
tmpl := "{{.Count}} items are made of {{.Material}}"
err := RunTempl(tmpl, sweaters)
if err != nil {
t.Error("Template failed")
}
}
func RunTempl(templ string, inv Inventory) error {
tmplObj, err := template.New("test").Parse(templ)
if err != nil {
return err
}
err = tmplObj.Execute(os.Stdout, inv)
if err != nil {
return err
}
return nil
}
⚠️ 注意事项:
- Go 测试文件必须以 _test.go 结尾,且包名与被测代码一致(此处均为 templateprint);
- testing 包不可出现在非测试源文件中,否则会触发“imported and not used”错误;
- 函数名 TestRunTempl 符合命名规范(Test + 驼峰),可被 go test 自动发现;
- 若需捕获模板执行输出(而非直接打印到 os.Stdout),建议改用 bytes.Buffer 进行可断言的测试,提升可靠性。
执行 go test -v 即可成功运行测试,验证模板逻辑是否正确。











