1 回答
TA贡献1804条经验 获得超7个赞
这是我基于此答案的解决方案:
osEnvFetcher.go:
package util
import (
"log"
"os"
"github.com/joho/godotenv"
)
var godotenvLoad = godotenv.Load
var logFatal = log.Fatal
type EnvFetcher interface {
Getenv(key string) string
}
type osEnvFetcher struct {}
func NewOsEnvFetcher() *osEnvFetcher {
err := godotenvLoad()
if err != nil {
logFatal("Error loading .env file")
}
return &osEnvFetcher{}
}
func (f *osEnvFetcher) Getenv(key string) string {
return os.Getenv(key)
}
osEnvFetcher_test.go:
package util
import (
"testing"
"errors"
)
func mockRestore(oGodotenvLoad func(...string) error, oLogFatal func(v ...interface{})) {
godotenvLoad = oGodotenvLoad
logFatal = oLogFatal
}
func TestOsEnvFetcher(t *testing.T) {
// Arrange
oGodotenvLoad := godotenvLoad
oLogFatal := logFatal
defer mockRestore(oGodotenvLoad, oLogFatal)
var godotenvLoadCalled = false
godotenvLoad = func(...string) error {
godotenvLoadCalled = true
return errors.New("parsed failure")
}
var logFatalCalled = false
var logFatalCalledWith interface{}
logFatal = func(v ...interface{}) {
logFatalCalled = true
logFatalCalledWith = v[0]
}
// Act
NewOsEnvFetcher()
// Assert
if !godotenvLoadCalled {
t.Errorf("godotenv.Load should be called")
}
if !logFatalCalled {
t.Errorf("log.Fatal should be called")
}
if logFatalCalledWith != "Error loading .env file" {
t.Errorf("log.Fatal should be called with: %s", logFatalCalledWith)
}
}
覆盖测试的结果:
☁ util [master] ⚡ go test -v -coverprofile cover.out
=== RUN TestOsEnvFetcher
--- PASS: TestOsEnvFetcher (0.00s)
PASS
coverage: 80.0% of statements
报道html记者:
- 1 回答
- 0 关注
- 122 浏览
添加回答
举报