There is no separate tool for unit testing in go, just call:
go test
Although there are additional testing framework for go, testing is included in the GO binary.
There are three levels, package, file and function.
go test
will call all test inside a directory which fulfill all three levels
If you test a function inside a package, the testing package should be named ${package_name}_test. This excludes the test code from the build binary, which makes the binary faster.
As an example I created a package “eventutils”, so my testfile has the package name “eventutils_test”.
GO allows the program files and the test files to be inside the same directory. So package main and package main_test or package eventutils and package eventutils_test are allowed in the same directory.
The file has to be named ${anything}_test.go. This does not have to be the name of the go file to test, but you find your test faster, if you do so.
The example has a file named eventutils_test.go
The function has to be named Test${anything}. All functions which names begin with Test will be called.
Testdata, i.e. additional data files like json file you need for the test should be put in the directory testdata. All files in this directory will be ignored by the go tool.
There are many options, you can read them with go help test|less
. These are the most commonly used:
cmd | effect |
---|---|
go test |
run all test in current directory |
go test ./... |
run all test in all directories |
go test -v |
verbose, show test outputs |
go test -run ${Testname} |
run a single test |