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 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误