To test functions which can finish in os.Exit(1) or similiar I am using this pattern:
func TestFoo(t *testing.T) {
if os.Getenv("TEST_USAGE") == "1" {
Foo()
return
}
cmd := exec.Command(os.Args[0], "-test.run=TestUsage")
cmd.Env = append(os.Environ(), "TEST_USAGE=1")
err := cmd.Run()
if e, ok := err.(*exec.ExitError); ok && !e.Success() {
fmt.Println("Foo test passed")
return
}
t.Errorf("Test ran with err %v, want exit status 1", err)
}
The test itself works fine, but the code being tested is not recorded as being covered if I use -cover or generate a HTML coverage report.
Is there a way to fix this? I have seen recommendations to use external packages but wonder if there is a way to fix this with the built-ins?