Created
December 5, 2024 06:07
-
-
Save yakuter/6556d918ecf0839aa809a3ef628cf53f to your computer and use it in GitHub Desktop.
StdoutTest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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