How to test Go function containing log.Fatal()

后端 未结 8 2258
南笙
南笙 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:58

    I have using the following code to test my function. In xxx.go:

    var logFatalf = log.Fatalf
    
    if err != nil {
        logFatalf("failed to init launcher, err:%v", err)
    }
    

    And in xxx_test.go:

    // TestFatal is used to do tests which are supposed to be fatal
    func TestFatal(t *testing.T) {
        origLogFatalf := logFatalf
    
        // After this test, replace the original fatal function
        defer func() { logFatalf = origLogFatalf } ()
    
        errors := []string{}
        logFatalf = func(format string, args ...interface{}) {
            if len(args) > 0 {
                errors = append(errors, fmt.Sprintf(format, args))
            } else {
                errors = append(errors, format)
            }
        }
        if len(errors) != 1 {
            t.Errorf("excepted one error, actual %v", len(errors))
        }
    }
    

提交回复
热议问题