如何在Golang中获得100%的代码覆盖率? [英] How to get 100% code coverage in Golang?

查看:260
本文介绍了如何在Golang中获得100%的代码覆盖率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获得100%的代码覆盖率,因为我无法在Golang中测试Fatals。





我发现了一些Q& As,包括这一个,但我失去了答案帖子是矛盾的。一方面可以检查Golang的代码覆盖率。另一方面,一些倡导者忽视例如的测试 log.Fatal(err),导致代码范围小于 100%






尝试

code> log.Fatal 由 panic 并感谢这个答案我能够测试所有的恐慌,并实现100%的代码覆盖率。




问题



尽管我能够获得100%的代码覆盖率,但我并不开心,因为我基本上滥用恐慌获得100%的代码覆盖率。根据这个答案 a <$ c使用$ c> panic :


当程序或其部分达到不可恢复状态时


基于此定义,我的代码中有多个片段可能引发恐慌,而 log.Fatal


解决方案

因为这个原因,我发现它对除main之外的所有函数和包都有用返回错误,而不是通话记录。直接致命。然后它可以是主要的决定退出或不出错。试图获得100%的测试覆盖率,不管在很多情况下可能会带来收益递减,所以也可以称得上足够好。


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

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%.


Attempts

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.


Problem

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.

解决方案

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.

这篇关于如何在Golang中获得100%的代码覆盖率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆