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
Release: 2024-11-16 16:48:03
Original
946 people have browsed it

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
    }
}
Copy after login

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")
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template