How to check a log/output in go test?

前端 未结 1 939
鱼传尺愫
鱼传尺愫 2021-02-12 14:42

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

func readByte(/*...*/){
    // ...
    if err != nil {
        fmt.Println(\"ERROR\")
        log.Print(\         


        
1条回答
  •  花落未央
    2021-02-12 15:33

    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
    $ 
    

    0 讨论(0)
提交回复
热议问题