Last active
December 5, 2024 06:23
-
-
Save yakuter/04b9466626c2fd1eec074157856e57d3 to your computer and use it in GitHub Desktop.
Testing Exit, Fatal, and Panic in Golang 2/3
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" | |
| "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