在golang中使用子流程测试时如何生成单元测试覆盖率? [英] How to generate unit test coverage when using subprocess testing in golang?

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

问题描述

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

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

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

  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



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



我试图获得尽可能多的代码覆盖尽可能。我不确定我是否错过了某些东西,或者是否有更简单的方法来做到这一点。或者,如果这是不可能的。



任何帮助表示赞赏。



谢谢



Amer

解决方案

我会将需要测试的逻辑分解为<$ c
$ b

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

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

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


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")

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.

Any help is appreciated.

Thanks

Amer

解决方案

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
}

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

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

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