普通网友 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());
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历