In this post we will review how to run tests, and check coverage for Go modules.
When creating a Go module, we add unit tests for anything we can, to avoid a bug from being detected only at system test stage, or worse at production.
To find which part of the code is tested, we can use the Go builtin tools:
go test ./... -race -covermode=atomic -coverprofile=../coverage.out
go tool cover -html=../coverage.out
The first command runs the tests, including check of a race condition issue, and prints the following output:
? example.com/app/detector/server/detectionstatuses [no test files] ok example.com/app/detector/server/detector 2.092s coverage: 98.6% of statements ok example.com/app/detector/server/extractor 0.240s coverage: 91.3% of statements ? example.com/app/detector/server/featuresnames [no test files] ok example.com/app/detector/server/headersparser 0.027s coverage: 100.0% of statements
For each package we get a indication whether the tests are OK/FAIL, and the coverage percent of the tests.
The second command, opens a browser with specific lines display. This enables us to find the code lines that are not tested.
Notice the coverage is considering only the current package tests, so if we have package a tests using package b code, b code will not be considered as a covered code.
No comments:
Post a Comment