Home >Backend Development >Golang >How to Capture and Verify Log Output in Go Tests?

How to Capture and Verify Log Output in Go Tests?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 16:48:03952browse

How to Capture and Verify Log Output in Go Tests?

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:

  • Create a buffer to capture the log output.
  • Redirect the default log output to the buffer using log.SetOutput(&buf).
  • Execute the readByte function.
  • Restore the default log output to os.Stderr using defer func() to prevent affecting subsequent tests.
  • Assert the expected log message using testify/assert.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn