go test 命令

简单示例

创建mod:

mkdir hello
cd hello

go mod init hello

创建echopackage实现Echo函数。

mkdir echo

echo/echo.go

package echo

import "fmt"

func Echo() {
  fmt.Println("------------------")
}

创建echo测试: echo/echo_test.go

package echo

import "testing"

func TestEcho(t *testing.T) {
  Echo()
}

go1.19.6不同目录位置执行test效果:

hello目录:

cd hello

go test
输出:
no Go files in /data/Project/GitLab/LGo/src/F/hello

go test echo
输出:
package echo is not in GOROOT (/data/docker_install/go/go/src/echo)

go test echo/echo_test.go 
输出:
# command-line-arguments [command-line-arguments.test]
echo/echo_test.go:6:3: undefined: Echo
FAIL	command-line-arguments [build failed]
FAIL

go test -v echo/echo_test.go echo/echo.go 
输出:
=== RUN   TestEcho
------------------
--- PASS: TestEcho (0.00s)
PASS
ok  	command-line-arguments	0.002s

hello/echo目录:

cd hello/echo

go test -v
输出:
=== RUN   TestEcho
------------------
--- PASS: TestEcho (0.00s)
PASS
ok  	hello/echo	0.002s

go test echo_test.go 
输出:
# command-line-arguments [command-line-arguments.test]
./echo_test.go:6:3: undefined: Echo
FAIL	command-line-arguments [build failed]
FAIL

go test -v echo_test.go echo.go 
输出:
=== RUN   TestEcho
------------------
--- PASS: TestEcho (0.00s)
PASS
ok  	command-line-arguments	0.002s

指定运行的测试方法: go test -v echo/echo_test.go echo/echo.go -test.run TestEcho

输出:


=== RUN   TestEcho
------------------
--- PASS: TestEcho (0.00s)
PASS
ok  	command-line-arguments	0.002s

若文件存在多级依赖,可以直接在包目录下执行go test,运行包下所有的测试文件

test注意问题

go test遇到的同一包下的变量报错undefined

参考文档: https://blog.csdn.net/helen920318/article/details/105017118

在简单示例中: go test hello/echo_test.go报错:

# command-line-arguments [command-line-arguments.test]
echo/echo_test.go:6:3: undefined: Echo
FAIL	command-line-arguments [build failed]
FAIL

原因是go test会为指定的源码文件生成一个虚拟代码包——“command-line-arguments”,而array_test.go引用了其他包中的数据并不属于代码包“command-line-arguments”,编译不通过,错误自然发生了。

因此,我们可以在go test的时候加上引用的包。

//执行整个测试文件
go test -v array_test.go array.go
//执行测试文件中的指定方法
go test -v array_test.go array.go -test.run TestNewArray
//若文件存在多级依赖,可以直接在包目录下执行go test,运行包下所有的测试文件
go test