For how to use testify packages for complex testing, please see
<<Go Unittest by testify>>
.
Golang has provided built-in testing framework composed of go test
command and
testing
package, here is simple example:
https://go.dev/doc/code#Testing
Table Driven
In go test we usually use table-driven
style, where test inputs and expected
outputs are listed in a struct and a loop to walk through them, for example:
1 | func TestXxx(t *testing.T) { |
Folder for Test Data
For large test data that needs to be read from outside, the go tool will ignore
a directory named testdata
, making it available to hold ancillary data needed
by the tests.
TestMain
If the test code contains a function:
1 | func TestMain(m *testing.M) { |
that function will be called instead of running the tests directly, this may come in handy when you need to do some global set-up/tear-down for your tests, see this example.
Run Test
To run test for specific packge:
1 | # ./... means all packages in this directory (and subdirectories) |
If you have build tags such as “integration”, “mock” in your test or dependency files head for example:
1 | // +build integration |
To include these taged test files in testing, please use -tags flag:
1 | go test -buildvcs=false \ |
If you don’t specify the correct -tags
then you will get error like:
1 | imports example.com/common.git/cassandra/setup: |
The -buildvcs
, -mod
, -race
, -tags
are build tags from go help build
.
There is logic to combine and use multiple tags, please see
Build Tag Boolean Logic.
NOTE that the
go test
will always run the test files that don’t have any build tag irrespective of-tags
specified or not.
Other test tags please see go help testflag
.
Test Coverage
For simplified coverage display only, just use -cover
flag:
1 | go test -cover ./... |
To generate coverage profile for detailed bad coverage analysis:
1 | # Generate simple coverage.out profile |
If you use -covermode=count
and then go tool the html will show you the
intensity of the statements calling count, hover the mouse over the line to see
the actual counts.
More details about cover
please see this go blog
<<The cover story
>>.