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 os.Exit(1)
the tests fail.
package main
import (
"log"
)
func hello() {
log.Print("Hello!")
}
func goodbye() {
log.Fatal("Goodbye!")
}
func init() {
log.SetFlags(0)
}
func main() {
hello()
goodbye()
}
Here are the hypothetical tests:
package main
import (
"bytes"
"log"
"testing"
)
func TestHello(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
hello()
wantMsg := "Hello!
"
msg := buf.String()
if msg != wantMsg {
t.Errorf("%#v, wanted %#v", msg, wantMsg)
}
}
func TestGoodby(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
goodbye()
wantMsg := "Goodbye!
"
msg := buf.String()
if msg != wantMsg {
t.Errorf("%#v, wanted %#v", msg, wantMsg)
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…