如何测试包含 log.Fatal() 的 Go 函数 [英] How to test Go function containing log.Fatal()

查看:12
本文介绍了如何测试包含 log.Fatal() 的 Go 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比如说,我有以下代码可以打印一些日志消息.我将如何测试是否记录了正确的消息?当 log.Fatal 调用 os.Exit(1) 时,测试失败.

Say, I had the following code that prints some log messages. How would I go about testing that the correct messages have been logged? As log.Fatal calls os.Exit(1) the tests fail.

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!
"
    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!
"
    msg := buf.String()
    if msg != wantMsg {
        t.Errorf("%#v, wanted %#v", msg, wantMsg)
    }
}

推荐答案

这类似于如何测试 os.Go 中的 Exit() 场景":您需要实现自己的记录器,默认情况下重定向到 log.xxx(),但在测试时给您机会, 将 log.Fatalf() 之类的函数替换为您自己的函数(不调用 os.Exit(1))

This is similar to "How to test os.Exit() scenarios in Go": you need to implement your own logger, which by default redirect to log.xxx(), but gives you the opportunity, when testing, to replace a function like log.Fatalf() with your own (which does not call os.Exit(1))

我对 os.Exit() 调用做了同样的测试rel="noreferrer">exit/exit.go:

I did the same for testing os.Exit() calls in exit/exit.go:

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

(这里,我的退出"函数是一个空函数,什么都不做)

(here, my "exit" function is an empty one which does nothing)

这篇关于如何测试包含 log.Fatal() 的 Go 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆