0

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?

adrianmcmenamin
  • 942
  • 1
  • 10
  • 36
  • 1
    This is how you should test code that calls `os.Exit()`: [Testing os.Exit scenarios in Go with coverage information (coveralls.io/Goveralls)](https://stackoverflow.com/questions/40615641/testing-os-exit-scenarios-in-go-with-coverage-information-coveralls-io-goverall/40801733#40801733) – icza Oct 11 '21 at 13:24

0 Answers0