doudongfu8006 2017-05-22 18:40
浏览 501
已采纳

如何在go测试中检查日志/输出?

I have this function that logs the error in some cases:

func readByte(/*...*/){
    // ...
    if err != nil {
        fmt.Println("ERROR")
        log.Print("Couldn't read first byte")
        return
    }
    // ...
}

Now, in the test file, I want to check the output error from this function:

    c.Assert(OUTPUT, check.Matches, "teste")

How can I access the log? I tried to put a buffer but it didn't work. What is the right way to catch this log without change my readByte function code?

  • 写回答

1条回答 默认 最新

  • dongnvwang8591 2017-05-22 20:45
    关注

    For example,

    readbyte_test.go:

    package main
    
    import (
        "bytes"
        "fmt"
        "io"
        "log"
        "os"
        "testing"
    )
    
    func readByte( /*...*/ ) {
        // ...
        err := io.EOF // force an error
        if err != nil {
            fmt.Println("ERROR")
            log.Print("Couldn't read first byte")
            return
        }
        // ...
    }
    
    func TestReadByte(t *testing.T) {
        var buf bytes.Buffer
        log.SetOutput(&buf)
        defer func() {
            log.SetOutput(os.Stderr)
        }()
        readByte()
        t.Log(buf.String())
    }
    

    Output:

    $ go test -v readbyte_test.go 
    === RUN   TestReadByte
    ERROR
    --- PASS: TestReadByte (0.00s)
        readbyte_test.go:30: 2017/05/22 16:41:00 Couldn't read first byte
    PASS
    ok      command-line-arguments  0.004s
    $ 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!