I am writing unit tests for my golang code, and there are a couple methods that I would like to be ignored when coverage is calculated. Is this possible? If so, how?
1 Answer
One way to do it would be to put the functions you don't want tested in a separate go file, and use a build tag to keep it from being included during tests. For example, I do this sometimes with applications where I have a main.go file with the main function, maybe a usage function, etc., that don't get tested. Then you can add a test tag or something, like go test -v -cover -tags test and the main might look something like:
//+build !test
package main
func main() {
// do stuff
}
func usage() {
// show some usage info
}
4 Comments
Oleg Sklyar
Any idea how to do the same without the need of a tag, i.e. by default?
Jason Coco
@OlegSklyar No, I don't believe you can do the same without the tag. The coverage report goes by all the code.
Yami Odymel
And the blank line after the
//+build test comment is important. +build comment must appear before package clause and be followed by a blank lineadamc
I've also discovered that the tag names cannot have a dash in them:
unit-tests won't work, whereas unit_tests will.
go tool cover -help), but that's different. You could write "tests" that exercise that code but don't really test anything, but that doesn't seem great.