如何用go test选择性测试Go模块,忽略未配置+build的测试?
解决方案
要实现只运行带有指定+build标签的测试,同时用./...遍历包,可以用以下两种方法:
方法一:给无关测试添加反向构建约束(适合长期维护)
给所有你暂时不想运行的测试文件开头添加反向构建约束,比如:
// +build !moduleA_feature1,!moduleA_feature3,!moduleB_feature1 package moduleX
这样当你执行go test -tags=moduleA_feature1,moduleA_feature3,moduleB_feature1 ./...时,所有带有反向约束的测试文件会被自动排除,只运行带有目标标签的测试。
如果是Go 1.17及以上版本,推荐同时使用新的//go:build指令,兼容性更好:
//go:build !moduleA_feature1 && !moduleA_feature3 && !moduleB_feature1 // +build !moduleA_feature1,!moduleA_feature3,!moduleB_feature1 package moduleX
方法二:用go list+grep过滤目标包(适合临时场景)
如果不想修改大量测试文件,可以用go list遍历所有包,再用grep筛选出包含目标构建标签的测试包,最后传给go test执行:
go test \ -coverprofile=coverage.out \ -tags=moduleB_feature1,moduleA_feature1,moduleA_feature3 \ $(go list -f '{{ if .TestGoFiles }}{{ .Dir }}{{ end }}' ./... | xargs grep -l "// +build moduleA_feature1\|// +build moduleA_feature3\|// +build moduleB_feature1")
这个命令的逻辑是:
go list ./...遍历所有包,-f参数只输出包含测试文件的包路径xargs grep -l找出测试文件中带有目标+build标签的包- 最后把这些包传给
go test,结合-tags参数只运行对应标签的测试
注意事项
- 构建标签必须放在测试文件的最开头,且和
package声明之间要空一行 - 如果测试文件同时属于多个标签,构建标签可以写在同一行(用逗号分隔),或者分成多行
内容的提问来源于stack exchange,提问作者RobGThai
相关产品推荐
相关产品推荐

