dougong2306 2017-08-21 13:03
浏览 118
已采纳

测试log.Fatalf进入吗?

I'd like to achieve 100% test coverage in go code. I am not able to cover the following example - can anyone help me with that?

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")
}

Some dumy test for that:

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) {
...
}

The issue is that log.Fatalf calls os.Exit and go engine dies.

  • I could modify the code and replace built-in library with my own - what makes the tests less reliable.
  • I could modify the code and create a proxy and a wrapper and a .... in other words very complex mechanism to change all calls to "log.Fatalf"
  • I could stop using built-in log package... what is equal to asking "how much is go built-in worth?"
  • I could live with not having 100% coverage
  • I could replace "log.Fataf" with something else - but then what is the point for built-in log.Fatalf?
  • I can try to mangle with system memory and depending on my OS replace memory address for the function (...) so do something obscure and dirty
  • Any other ideas?
  • 写回答

2条回答 默认 最新

  • dongxieyou3314 2017-08-21 13:14
    关注

    Use log.Print instead of log.Fatal and return the error value that you declared in signature of function checkIfReadable. Or don't the error it and return it to some place that knows better how to handle it.

    The function log.Fatal is strictly for reporting your program's final breath.

    Calling log.Fatal is a bit worse than calling panic (there is also log.panic), because it does not execute deferred calls. Remember, that overusing panic in Go is considered a bad style.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?