package main import ( "github.com/stretchr/testify/assert" "os" "os/exec" "testing" ) func TestGetEnvUndefined(t *testing.T) { key := "TEST_VAR" expectedErrorString := "exit status 1" // Run the crashing code when FLAG is set if os.Getenv("GO_CRASHER") == "1" { getEnv(key) return } // Run the test in a subprocess - this is a hack! cmd := exec.Command(os.Args[0], "-test.run=TestGetEnvUndefined") cmd.Env = append(os.Environ(), "GO_CRASHER=1") err := cmd.Run() // Cast the error as *exec.ExitError and compare the result e, ok := err.(*exec.ExitError) assert.True(t, ok) // check if its an error assert.Equal(t, expectedErrorString, e.Error()) // check if it exited } func TestGetEnvDefined(t *testing.T) { key := "TEST_VAR" val := "1" os.Setenv(key, val) actual := getEnv(key) assert.Equal(t, val, actual) }