unit-testing - 如何使用 Go 日志包 glog 测试代码?

标签 unit-testing go

我已经实现了一个类型包装 glog,这样我就可以在日志消息中添加一个前缀来标识我程序中日志的发射器,并且我可以更改每个发射器的日志级别。

我如何实现单元测试?问题是 glog 将文本输出到 stdErr。

代码很简单,但我希望像其余代码一样进行单元测试和 100% 的覆盖率。这种编程工作已经付出了代价。

最佳答案

捕获标准错误的测试:

package main

import (
    "bytes"
    "io"
    "os"
    "testing"

    "github.com/golang/glog"
    "strings"
)

func captureStderr(f func()) (string, error) {
    old := os.Stderr // keep backup of the real stderr
    r, w, err := os.Pipe()
    if err != nil {
        return "", err
    }
    os.Stderr = w

    outC := make(chan string)
    // copy the output in a separate goroutine so printing can't block indefinitely
    go func() {
        var buf bytes.Buffer
        io.Copy(&buf, r)
        outC <- buf.String()
    }()

    // calling function which stderr we are going to capture:
    f()

    // back to normal state
    w.Close()
    os.Stderr = old // restoring the real stderr
    return <-outC, nil
}

func TestGlogError(t *testing.T) {
    stdErr, err := captureStderr(func() {
        glog.Error("Test error")
    })
    if err != nil {
        t.Errorf("should not be error, instead: %+v", err)
    }
    if !strings.HasSuffix(strings.TrimSpace(stdErr), "Test error") {
        t.Errorf("stderr should end by 'Test error' but it doesn't: %s", stdErr)
    }
}

运行测试:

go test -v
=== RUN   TestGlogError
--- PASS: TestGlogError (0.00s)
PASS
ok      command-line-arguments  0.007s

关于unit-testing - 如何使用 Go 日志包 glog 测试代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41247206/

相关文章:

c# - 测试结果中未复制所有程序集 - MS 测试

c++ - 使用 Gtest 如何在 ON_CALL 中返回不同的值?

arrays - Go中的JSON解码有符号整数数组

go - 在 Go 中访问 map 接口(interface)值

go - 在 golang 中声明一个空的 map[string]interface{} 的内存成本/开销是多少?

ios - 单元测试单例 : mock and swizzle

java - 使用 ASM 字节码进行测试

go - 如何检查一个包直接依赖/间接依赖另一个包?

java - 在一份 testNG 报告中显示多个测试套件的所有失败测试

go - 安排任务/消息以供以后处理/交付