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
}
Share:
11,598

Related videos on Youtube

jonbonazza
Author by

jonbonazza

Updated on June 07, 2022

Comments

  • jonbonazza
    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
      twotwotwo over 9 years
      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.
    • jonbonazza
      jonbonazza over 9 years
      Yea, it doesn't seem that there is a way to test the code, but ignore it in coverage reports... :/
  • Oleg Sklyar
    Oleg Sklyar over 8 years
    Any idea how to do the same without the need of a tag, i.e. by default?
  • Jason Coco
    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
    Yami Odymel over 7 years
    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
  • adamc
    adamc over 6 years
    I've also discovered that the tag names cannot have a dash in them: unit-tests won't work, whereas unit_tests will.