Accessing Logs in Go Tests
In Go testing, verifying the log output of a function can be challenging, especially when the function itself logs the error directly.
To capture the log output, a common solution is to redirect the default log output to a buffer before executing the function under test.
Example:
Consider the following readByte function:
func readByte(/*...*/) { if err != nil { fmt.Println("ERROR") log.Print("Couldn't read first byte") return } }
To test the log output, we can use the following approach in the test file:
package main import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestReadByte(t *testing.T) { var buf bytes.Buffer log.SetOutput(&buf) defer func() { log.SetOutput(os.Stderr) }() readByte() output := buf.String() assert.Contains(t, output, "Couldn't read first byte") }
In this example, we:
The above is the detailed content of How to Capture and Verify Log Output in Go Tests?. For more information, please follow other related articles on the PHP Chinese website!