为 Go 测试设置环境变量

Set environment variable for Go tests

我正在尝试 运行 我的 Go 测试是这样的,设置一个环境变量:

FOO=BAR go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s

在我的测试中我做了:

log.Print(os.Getenv("FOO"))

其中returns一个空字符串。为什么没有设置 FOO?

FOO=BAR bash -c 'go list ./... | grep -v vendor | xargs -n1 go test -timeout=3s'

可以在问题的答案中找到为什么原始命令不起作用的一个很好的解释:https://unix.stackexchange.com/questions/134735/environment-variables-are-not-set-when-my-function-is-called-in-a-pipeline

这不是为管道设置变量的方式。参见:

 FOO=BAR echo "AAA" | FOO=WAZ printenv | grep FOO

我喜欢用godotenv in command mode

godotenv -f ./.env go test ./internal/... -cover