Use t.Setenv(key, value) to set an environment variable for the duration of a test function, ensuring it is automatically restored afterward. This prevents test pollution and ensures isolation between tests.
func TestMyFunction(t *testing.T) {
t.Setenv("MY_VAR", "test_value")
// Your test code here
val := os.Getenv("MY_VAR")
if val != "test_value" {
t.Errorf("expected test_value, got %s", val)
}
}