Golang测试中出现"testing: warning: no tests to run"警告的解决方法
Golang测试中出现"testing: warning: no tests to run"警告的解决方法 我做错了什么?我还在学习并试图弄清楚测试,但显然我有些地方搞错了,尽管搜索了很多资料还是没弄明白。我遗漏了什么?先谢谢了!!
mainFile.go 文件内容:
package main
func fourPlusFour() (r int) {
return 4 + 4
}
mainFile_test.go 文件内容:
package main
import "testing"
func testfourPlusFour(t *testing.T) {
if fourPlusFour() != 7 {
t.Error("You Failed")
}
}
终端命令是:~/go/src/user/testingTest$ go test 终端输出为:
testing: warning: no tests to run
PASS
ok user/testingTest 0.002s
go env 输出:
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/user1/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/user1/go"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build486771635=/tmp/go-build -gno-record-gcc-switches"
更多关于Golang测试中出现"testing: warning: no tests to run"警告的解决方法的实战教程也可以访问 https://www.itying.com/category-94-b0.html
不太明白:
我在两个文件中将包名改为mytest,但go test的输出结果没有变化
更多关于Golang测试中出现"testing: warning: no tests to run"警告的解决方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
更改包的名称,将两个文件中的mytest或任何其他名称修改后重新执行
将你的方法名改为大写字母 TestFourPlusFour()
func main() {
fmt.Println("hello world")
}
问题在于测试函数的命名不符合Go测试框架的要求。在Go中,测试函数必须以Test开头(注意大写T),后跟一个首字母大写的名称,并且接受一个*testing.T参数。
将testfourPlusFour改为TestFourPlusFour即可解决:
package main
import "testing"
func TestFourPlusFour(t *testing.T) {
if fourPlusFour() != 8 { // 注意:4+4=8,不是7
t.Error("Expected 8, but got", fourPlusFour())
}
}
运行go test后应该看到:
--- FAIL: TestFourPlusFour (0.00s)
mainFile_test.go:6: Expected 8, but got 8
FAIL
exit status 1
FAIL user/testingTest 0.002s
或者如果修正期望值为8:
func TestFourPlusFour(t *testing.T) {
if fourPlusFour() != 8 {
t.Error("Expected 8, but got", fourPlusFour())
}
}
则会看到:
PASS
ok user/testingTest 0.002s
Go测试框架通过函数名的Test前缀和*testing.T参数来识别测试函数。不符合此命名约定的函数不会被go test命令执行。


