Skip to content

Instantly share code, notes, and snippets.

@yakuter
Created December 5, 2024 06:07
Show Gist options
  • Save yakuter/6556d918ecf0839aa809a3ef628cf53f to your computer and use it in GitHub Desktop.
Save yakuter/6556d918ecf0839aa809a3ef628cf53f to your computer and use it in GitHub Desktop.
StdoutTest
package main
import (
"bytes"
"fmt"
"io"
"os"
"testing"
)
func TestStdoutCapture(t *testing.T) {
// Save the original stdout
originalStdout := os.Stdout
// Create a new buffer and redirect stdout
var buf bytes.Buffer
r, w, err := os.Pipe()
if err != nil {
t.Fatalf("Failed to create pipe: %v", err)
}
os.Stdout = w
// Call the function to be tested
fmt.Println("Hello, World!")
// Stop writing and restore stdout
w.Close()
os.Stdout = originalStdout
io.Copy(&buf, r)
// Verify the output
output := buf.String()
if output != "Hello, World!\n" {
t.Errorf("Expected: \"Hello, World!\\n\", Got: \"%s\"", output)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment