douzepao0281
2014-09-24 16:42
浏览 99
已采纳

在Golang中使用子流程测试时,如何生成单元测试覆盖率?

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

图片转代码服务由CSDN问答提供 功能建议

我对大多数代码都有单元测试。 但是我无法弄清楚如何为main包中的main()中的某些代码生成单元测试覆盖率。

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

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

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

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

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

我尝试实现尽可能多的代码覆盖率 。 我不确定我是否缺少某些东西,或者是否有更简单的方法来做到这一点。

感谢您的任何帮助。

谢谢

Amer

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongtou9934 2014-09-24 18:34
    已采纳

    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.

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题