Testing 如何在go测试中检查日志/输出?
我有一个函数,在某些情况下记录错误:Testing 如何在go测试中检查日志/输出?,testing,go,Testing,Go,我有一个函数,在某些情况下记录错误: func readByte(/*...*/){ // ... if err != nil { fmt.Println("ERROR") log.Print("Couldn't read first byte") return } // ... } 现在,在测试文件中,我想检查此函数的输出错误: c.Assert(OUTPUT, check.Matches, "teste
func readByte(/*...*/){
// ...
if err != nil {
fmt.Println("ERROR")
log.Print("Couldn't read first byte")
return
}
// ...
}
现在,在测试文件中,我想检查此函数的输出错误:
c.Assert(OUTPUT, check.Matches, "teste")
如何访问日志?我试着放一个缓冲器,但没用。在不更改readByte函数代码的情况下捕获此日志的正确方法是什么
readbyte\u测试。转到
:
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())
}
输出:
$ 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
$
将日志写入缓冲区有什么不起作用?缓冲区是空的。输出返回“”。我检查日志是否正在写入,但我的缓冲区总是空的。因此,显示如何写入缓冲区。您没有理由不能写入缓冲区并在以后检查它。什么是
log.Print
?Go的stdliblog
package?