Ignore code blocks in Golang test coverage calculation
11,598
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
}
Related videos on Youtube
Author by
jonbonazza
Updated on June 07, 2022Comments
-
jonbonazza almost 2 years
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?
-
twotwotwo over 9 yearsI don't know a way. You can get profiles by function with -func (see blog.golang.org/cover or run
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. -
jonbonazza over 9 yearsYea, it doesn't seem that there is a way to test the code, but ignore it in coverage reports... :/
-
-
Oleg Sklyar over 8 yearsAny idea how to do the same without the need of a tag, i.e. by default?
-
Jason Coco almost 8 years@OlegSklyar No, I don't believe you can do the same without the tag. The coverage report goes by all the code.
-
Yami Odymel over 7 yearsAnd the blank line after the
//+build test
comment is important.+build comment must appear before package clause and be followed by a blank line
-
adamc over 6 yearsI've also discovered that the tag names cannot have a dash in them:
unit-tests
won't work, whereasunit_tests
will.