
Go 的 Example 函数需与至少一个 Test 函数共存于 _test.go 文件中才能被 go test 识别并执行;仅含 Example 而无任何 Test 函数时,go test 会报“no tests to run”警告。
go 的 `example` 函数需与至少一个 `test` 函数共存于 `_test.go` 文件中才能被 `go test` 识别并执行;仅含 example 而无任何 test 函数时,`go test` 会报“no tests to run”警告。
在 Go 中,Example 函数用于提供可运行的文档示例,并支持自动验证输出(通过 // Output: ... 注释)。但它们不是独立的测试用例,而是依赖 go test 的示例执行机制——该机制仅在测试包被激活时启用,而激活的前提是:当前文件中至少存在一个以 Test 开头的测试函数(即 func TestXxx(t *testing.T))。
你遇到的错误:
testing: warning: no tests to run
根本原因正是:xxxx_test.go 文件中只定义了 ExampleMethod1(),却未定义任何 Test 函数。Go 的测试驱动器发现没有可执行的测试入口,便跳过整个文件(包括 Example),导致示例无法运行。
✅ 正确做法:
在 xxxx_test.go 中添加一个最小化的测试函数(即使内容为空),即可激活示例执行:
// xxxx_test.go
package yourpackage
import (
"fmt"
"testing"
)
// 示例函数:会被 go test -v 自动发现并运行(输出匹配则通过)
func ExampleMethod1() {
fmt.Printf("result: %x", Method1())
// Output: xxxx
}
// 必须存在至少一个 Test 函数,否则 go test 忽略整个文件
func TestDummy(t *testing.T) {
// 可为空,仅用于触发测试框架初始化
}然后运行:
go test -v
你将看到类似输出:
=== RUN ExampleMethod1 --- PASS: ExampleMethod1 (0.00s)
⚠️ 注意事项:
-
Example函数名必须以Example开头,且首字母大写的后缀需与被测标识符一致(如ExampleMethod1对应Method1); -
// Output:注释必须紧接在函数末尾(不可有空行),且输出内容需与实际fmt打印完全一致(包括空格、换行); - 不要单独运行单个
_test.go文件(如go test -v xxxx_test.go),而应运行整个包:go test -v(在包目录下)或go test -v ./...(子模块); - 若使用
go test -run=^$(跳过所有 Test)仍想运行 Example,可用go test -example=. -v显式启用示例模式(Go 1.21+ 支持),但前提是包中仍有Test函数存在——这是 Go 测试模型的硬性要求。
简言之:Example 是测试生态的“附属能力”,不是替代 Test 的方案。有 Test,才有 Example 的舞台。

















