How to test Go function containing log.Fatal()

后端 未结 8 2240
南笙
南笙 2020-12-09 08:10

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 o

8条回答
  •  轮回少年
    2020-12-09 08:51

    I've combined answers from different sources to produce this:

    import (
        "bufio"
        "bytes"
        "errors"
        "fmt"
        "io/ioutil"
        "log"
        "os"
        "os/exec"
        "os/user"
        "strings"
        "testing"
    
        "bou.ke/monkey"
        "github.com/stretchr/testify/assert"
        "github.com/stretchr/testify/mock"
        "github.com/stretchr/testify/require"
    )
    
    
    func TestCommandThatErrors(t *testing.T) {
        fakeExit := func(int) {
            panic("os.Exit called")
        }
        patch := monkey.Patch(os.Exit, fakeExit)
        defer patch.Unpatch()
    
        var buf bytes.Buffer
        log.SetOutput(&buf)
    
        for _, tc := range []struct {
            cliArgs       []string
            expectedError string
        }{
            {
                cliArgs:       []string{"dev", "api", "--dockerless"},
                expectedError: "Some services don't have dockerless variants implemented yet.",
            },
        } {
            t.Run(strings.Join(tc.cliArgs, " "), func(t *testing.T) {
                harness := createTestApp()
                for _, cmd := range commands {
                    cmd(harness.app)
                }
    
                assert.Panics(t, func() { harness.app.run(tc.cliArgs) })
                assert.Contains(t, buf.String(), tc.expectedError)
                buf.Reset()
            })
        }
    }
    

    Works great :)

提交回复
热议问题