Skip to content

Instantly share code, notes, and snippets.

@yakuter
Last active December 5, 2024 06:23
Show Gist options
  • Save yakuter/04b9466626c2fd1eec074157856e57d3 to your computer and use it in GitHub Desktop.
Save yakuter/04b9466626c2fd1eec074157856e57d3 to your computer and use it in GitHub Desktop.
Testing Exit, Fatal, and Panic in Golang 2/3
package main
import (
"bytes"
"log"
"os"
"testing"
)
func TestLogFatal(t *testing.T) {
// Save original os.Exit
originalExit := os.Exit
defer func() { os.Exit = originalExit }()
exitCalled := false
// Mock os.Exit
os.Exit = func(code int) {
exitCalled = true
panic("os.Exit called")
}
// Capture stderr
var buf bytes.Buffer
log.SetOutput(&buf)
defer log.SetOutput(os.Stderr)
// Test the function
func() {
defer func() { recover() }()
log.Fatal("Fatal error occurred")
}()
// Verify output
if !exitCalled {
t.Errorf("os.Exit was not called")
}
if !bytes.Contains(buf.Bytes(), []byte("Fatal error occurred")) {
t.Errorf("Expected log message not found: %s", buf.String())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment