2015-11-23 14:21

如何在Golang中获得100%的代码覆盖率? [重复]

This question already has an answer here:

I cannot get 100% code coverage as I cannot test Fatals in Golang.

enter image description here

I have found some Q&As including this one, but I am lost as the answers to the posts are contradictory. On the one hand it is possible to check the code coverage in Golang. On the other hand some advocate to ignore the testing of e.g. log.Fatal(err), resulting in a code coverage of less than 100%.


As a workaround I replaced all log.Fatal by panic and thanks to this answer I am able to test all the panics and to achieve 100% code coverage.


Although I am able to get 100% code coverage I am not happy as I am basically misusing panic to get 100% code coverage. According to this answer a panic is used:

when the program, or its part, has reached an unrecoverable state

Based on this definition there are multiple snippets in my code that can throw a panic, while a log.Fatal should be used.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dougan7657 dougan7657 6年前

    For this reason I find it useful for all functions and packages besides main to return errors rather than call log.Fatal directly. Then it can be main's decision to exit or not on errors. Trying to get 100% test coverage no matter what may give diminishing returns in a lot of cases though, so it may also be ok to call it good enough.

    点赞 评论 复制链接分享
  • dongxing4196 dongxing4196 6年前

    One trick I can suggest is instead of calling log.Fatal, make your own fatal func with the same signature:

    var fatal func(...interface{}) = log.Fatal

    anywhere in your package. It can be unexported so other packages cannot set or use it. Then in your test you can replace it with:

    fatal = func(v ...interface){

    or whatever you want to do.

    I use this kind of trick when I need to test time.Now or something of this sort.

    点赞 评论 复制链接分享