在 Golang 子流程测试中使用命令行标志时如何生成单元测试覆盖率? [英] How to generate unit test coverage when using command line flags in Golang subprocess testing?

查看:31
本文介绍了在 Golang 子流程测试中使用命令行标志时如何生成单元测试覆盖率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我们的大部分代码进行了单元测试.但是我无法弄清楚如何为 main 包中的 main() 中的某些代码生成单元测试覆盖率.

I have unit tests for most of our code. But I cannot figure out how to generate unit tests coverage for certain code in main() in main package.

主要功能非常简单.它基本上是一个选择块.它读取标志,然后调用另一个函数/执行某事,或者只是在屏幕上打印帮助.但是,如果命令行选项设置不正确,它将以各种错误代码退出.因此,需要进行子流程测试.

The main function is pretty simple. It is basically a select block. It reads flags, then either call another function/execute something, or simply print help on screen. However, if commandline options are not set correctly, it will exit with various error codes. Hence, the need for sub-process testing.

我尝试了子流程测试技术,但修改了代码,使其包含覆盖标志:

I tried sub-process testing technique but modified code so that it include flag for coverage:

cmd := exec.Command(os.Args[0], "-test.run=TestMain -test.coverprofile=/vagrant/ucover/coverage2.out")

这是原始代码:https://talks.golang.org/2014/testing.slide#23上面幻灯片的解释:http://youtu.be/ndmB0bj7eyw?t=47m16s

Here is original code: https://talks.golang.org/2014/testing.slide#23 Explanation of above slide: http://youtu.be/ndmB0bj7eyw?t=47m16s

但它不会生成封面配置文件.我一直无法弄清楚为什么不.它确实为执行测试的主进程生成覆盖配置文件,但是在子进程中执行的任何代码当然不会被标记为已执行.

But it doesn't generate cover profile. I haven't been able to figure out why not. It does generate cover profile for main process executing tests, but any code executed in sub-process, of course, is not marked as executed.

我尝试实现尽可能多的代码覆盖率.我不确定我是否遗漏了什么,或者是否有更简单的方法来做到这一点.或者,如果这是不可能的.

I try to achieve as much code coverage as possible. I am not sure if I am missing something or if there is an easier way to do this. Or if it is just not possible.

感谢任何帮助.

谢谢

阿米尔

推荐答案

我会将需要测试的逻辑从 main() 中分解出来:

I would factor the logic that needs to be tested out of main():

func main() {
    start(os.Args)
}

func start(args []string) {
    // old main() logic
}

通过这种方式,您可以对 start() 进行单元测试,而无需改变 os.Args.

This way you can unit-test start() without mutating os.Args.

这篇关于在 Golang 子流程测试中使用命令行标志时如何生成单元测试覆盖率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆