普通网友 2018-07-11 04:21
浏览 248
已采纳

我应该使用哪种方法在golang中测试func main()?

I have a function main() in main.go that does the job and all other functions are below it (I did not include them here). So, when I write tests for all funcs that are included in main, I can test them. But the code coverage is low because it shows that I did not cover code from my main func.

I know that there is a TestMain func in the testing library that should do the job, but I just cannot get how to get it to work so that the tests cover func main().

Below is my main() func which is not covered by tests...

func main() {
c, err := getConfig()
if err != nil {
    log.Fatal(err)
}
slideshows, err := getSlideshows(c)
if err != nil {
    log.Fatal(err)
}

displaySlideshows(slideshows)

}

Also, I did not find much about it on the internet, so, if this is a stupid question, please, explain to me why this is such a dum problem and where I should search for solutions!

I will appreciate any help!

  • 写回答

1条回答 默认 最新

  • dshmvqnl98119 2018-07-11 04:31
    关注

    You can check out "Go coverage with external tests", by Filippo Valsorda:

    We create a dummy test that executes main(), we put it behind a build tag, compile a binary with go test -c -cover and then run only that test instead of running the regular binary.

    Here's what the rrdns_test.go file looks like:

    Note the empty line between the build tag and package:

    // +build testrunmain
    
    package main
    
    import "testing"
    
    func TestRunMain(t *testing.T) {
        main()
    }
    

    We compile the binary like this:

    $ go test -coverpkg="rrdns/..." -c -tags testrunmain rrdns
    

    And then when we want to collect coverage information, we execute this instead of ./rrdns (and run our test battery as usual):

    $ ./rrdns.test -test.run "^TestRunMain$" -test.coverprofile=system.out
    

    You must return from main() cleanly for the profile to be written to disk; in RRDNS we do that by catching SIGINT. You can still use command line arguments and standard input normally, just note that you will get two lines of extra output from the test framework.

    This is similar to this answer which proposes:

    func main() {
        os.Exit(doFunc());
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?