I have tried couple of approaches (shown below) but I don't like any of them. So I decided to ask the community if there is a better way to do it.
Approach 1
Pass database credentials as arguments:
go test -args -db_user=test -db_pass=secret
Then use it in tests as:
package my_test
var dbUser = flag.String("db_user", "", "test database user")
var dbPass = flag.String("db_pass", "", "test database password")
func TestSomething(t *testing.T) {
db := open(*dbUser, *dbPass)
}
Approach 2
Set environment variables before running tests:
$ export TEST_DB_USER=user
$ export TEST_DB_PASS=secret
$ go test
or
$ TEST_DB_USER=user TEST_DB_PASS=secret go test -v
Then use it in tests as:
package my_test
var dbUser = flag.String("db_user", "", "test database user")
var dbPass = flag.String("db_pass", "", "test database password")
func TestSomething(t *testing.T) {
db := open(os.Getenv("TEST_DB_USER"), os.Getenv("TEST_DB_PASS"))
}
Approach 3
Use .env.test
file and github.com/joho/godotenv
package to load database connection credentials before running tests.
Environment variables tend to be best for this for the following reasons:
But overall, this is too broad a question. The ultimate answer depends on the people working on the project with a daily need to run tests. It also depends massively on your test infrastructure.
And finally: if this is for unittests, you shouldn't need database credentials, external services should be mocked. You also don't want contributors to need database credentials to run unittests.
If this is for integration tests, your test infrastructure will be the most important factor.