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

在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

  • 写回答

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

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler