Can't use godotenv when running tests
Author: adamcohenCreated Oct 13, 2017Updated May 16, 2026
I've added godotenv to my project and it works fine when running the compiled binary, but it fails when running my tests:
$ go test ./...
2017/10/13 16:22:37 Error loading .env fileopen .env: no such file or directoryThis is happening because the tests are being run in the following temp dir location:
/var/folders/yh/7x8fqv696sb1673313nk8_m80000gn/T/go-build041463486/github.com/myrepo/identity/server/_testand it can't find the .env file. Can anyone tell me how to fix this issue? Do I need to specify the absolute path to the .env file? I'm using the following code to load the .env file without specifying a path:
err = godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file", err)
}Source: joho/godotenv