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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色