忽略 Golang 测试覆盖率计算中的代码块。

huangapple go评论80阅读模式
英文:

Ignore code blocks in Golang test coverage calculation

问题

在编写我的 Golang 代码的单元测试时,有几个方法我希望在计算覆盖率时被忽略。这是否可能?如果是,应该如何实现?

英文:

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

得分: 19

一种方法是将不想进行测试的函数放在一个单独的go文件中,并使用构建标签来防止在测试期间包含它。例如,我有时会在应用程序中这样做,其中有一个main.go文件,包含主函数、可能是一个使用函数等,这些函数不会被测试。然后,你可以添加一个测试标签或类似的东西,比如go test -v -cover -tags test,主函数可能如下所示:

//+build !test

package main

func main() {
    // 做一些事情
}

func usage() {
    // 显示一些使用信息
}
英文:

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
}

huangapple
  • 本文由 发表于 2014年8月27日 00:47:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/25511076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定