比方说,我使用以下代码打印一些日志(log)消息.我应该如何着手测试是否记录了正确的消息?当log.Fatal呼叫os.Exit(1)时,测试失败.

package main

import (
    "log"
)

func hello() {
    log.Print("Hello!")
}

func goodbye() {
    log.Fatal("Goodbye!")
}

func init() {
    log.SetFlags(0)
}

func main() {
    hello()
    goodbye()
}

以下是假设测试:

package main

import (
    "bytes"
    "log"
    "testing"
)


func TestHello(t *testing.T) {
    var buf bytes.Buffer
    log.SetOutput(&buf)

    hello()

    wantMsg := "Hello!\n"
    msg := buf.String()
    if msg != wantMsg {
        t.Errorf("%#v, wanted %#v", msg, wantMsg)
    }
}

func TestGoodby(t *testing.T) {
    var buf bytes.Buffer
    log.SetOutput(&buf)

    goodbye()

    wantMsg := "Goodbye!\n"
    msg := buf.String()
    if msg != wantMsg {
        t.Errorf("%#v, wanted %#v", msg, wantMsg)
    }
}

推荐答案

这类似于"How to test os.Exit() scenarios in Go":您需要实现自己的记录器,默认情况下重定向到log.xxx(),但是在测试时,您可以用自己的函数(不调用os.Exit(1))替换log.Fatalf()这样的函数.

我对exit/exit.go个电话中的os.Exit()个进行了同样的测试:

exiter = New(func(int) {})
exiter.Exit(3)
So(exiter.Status(), ShouldEqual, 3)

(这里,我的"exit"函数是一个空函数,什么也不做)

Go相关问答推荐

将Go程序导出到WASM—构建约束排除所有Go文件

如何在GoFr中为生产和本地环境设置不同的配置?

即使HTTP服务器正在使用GO和Protobuf、SQL Server启动,请求也不返回结果

Go中的net.SplitHostPort(r.RemoteAddr)安全性

如何在VSCode中为特定的.go文件创建调试配置?

GORM:一个表的两个外键

go中跨域自定义验证的问题

无法读取postman 中的表单数据

使用Go和Operator SDK通过API调用设置Kubernetes Pods的安装步骤

如何使用名称具有包名称的嵌套 struct 启动 go struct

Go:如何在将 float64 转换为 float32 时判断精度损失

Apache Beam 在 Go 中从 PCollection 中 Select 前 N 行

函数实现接口时的模式名称是什么?

使用 golang 生成 vim

具有两个或多个模型的 GORM 查询

如何将文件上传到 Google Drive,并与使用服务帐户和 Golang 的任何人共享

Golang泛型在用作 map 元素时不起作用

在 go 中将运行命令的标准输出发送到其标准输入

在 Raspberry Pi4 上下载 Go Mod

为什么 template.ParseFiles() 没有检测到这个错误?