我想在Go代码中达到100%的测试覆盖率。我无法涵盖以下示例-有人可以帮助我吗?
package example
import (
"io/ioutil"
"log"
)
func checkIfReadable(filename string) (string, error) {
_, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("Cannot read the file... how to add coverage test for this line ?!?")
}
return "", nil
}
func main() {
checkIfReadable("dummy.txt")
}
Run Code Online (Sandbox Code Playgroud)
一些傻瓜测试:
package example
import (
"fmt"
"testing"
)
func TestCheckIfReadable(t *testing.T) {
someResult, err := checkIfReadable("dummy.txt")
if len(someResult) > 0 {
fmt.Println("this will not print")
t.Fail()
}
if err != nil {
fmt.Println("this will not print")
t.Fail()
}
}
func TestMain(t *testing.T) {
...
}
Run Code Online (Sandbox Code Playgroud)
问题是log.Fatalf调用os.Exit并退出引擎。
使用log.Print代替log.Fatal并返回您在function的签名中声明的错误值checkIfReadable。或者不要将其错误,然后将其返回到更了解如何处理它的地方。
该功能log.Fatal严格用于报告程序的最终呼吸。
调用log.Fatal比调用panic(还有log.panic)要差一些,因为它不会执行延迟的调用。请记住,panic在Go 中过度使用被认为是不好的风格。