英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论