How to test Go function containing log.Fatal()

后端 未结 8 2267
南笙
南笙 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 09:01

    If you're using logrus, there's now an option to define your exit function from v1.3.0 introduced in this commit. So your test may look something like:

    func Test_X(t *testing.T) {
        cases := []struct{
            param string
            expectFatal bool
        }{
            {
                param: "valid",
                expectFatal: false,
            },
            {
                param: "invalid",
                expectFatal: true,
            },
        }
    
        defer func() { log.StandardLogger().ExitFunc = nil }()
        var fatal bool
        log.StandardLogger().ExitFunc = func(int){ fatal = true }
    
        for _, c := range cases {
            fatal = false
            X(c.param)
            assert.Equal(t, c.expectFatal, fatal)
        }
    }
    

提交回复
热议问题