33

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?

2
  • I 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. Commented Aug 26, 2014 at 18:08
  • Yea, it doesn't seem that there is a way to test the code, but ignore it in coverage reports... :/ Commented Aug 26, 2014 at 21:39

1 Answer 1

19

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
}
Sign up to request clarification or add additional context in comments.

4 Comments

Any idea how to do the same without the need of a tag, i.e. by default?
@OlegSklyar No, I don't believe you can do the same without the tag. The coverage report goes by all the code.
And the blank line after the //+build test comment is important. +build comment must appear before package clause and be followed by a blank line
I've also discovered that the tag names cannot have a dash in them: unit-tests won't work, whereas unit_tests will.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.