初始化功能中断单元测试

Ale*_*sta 1 unit-testing go

在要测试的软件包中,我有一个init函数,该函数可以加载配置文件,其中包含一些我想用来运行应用程序的内容。但是,我不想在运行单元测试时触发此init函数。

有什么方法可以跳过或阻止在单元测试期间调用此init函数?

一些片段来说明这个问题:

func init() {
    var err error // Necessary to prevent config variable shadowing
    config, err = loadConfig("./client/config.yml")
    if err != nil {
        log.Fatal(err)
    }
}

func loadConfig(filepath string) (*Config, error) {
    viper.SetConfigFile(filepath)
    if err := viper.ReadInConfig(); err != nil {
        return nil, fmt.Errorf("Error loading config file: %s", err)
    }
  (...)
}

// New returns a Config value(!)
func New() Config {
    return *config
}
Run Code Online (Sandbox Code Playgroud)

一个测试用例:

func TestNew(t *testing.T) {
    expected := &Config{}
    observed := New()
    if !reflect.DeepEqual(observed, expected) {
        t.Errorf("observed %+v. expecting %+v\n", observed, expected)
    }
}
Run Code Online (Sandbox Code Playgroud)

mko*_*iva 5

我不确定是否有更好的方法来执行此操作,但是如果考虑到在init运行func 之前已初始化程序包级变量的事实,则可以使用标志来告诉您是否正在运行测试。

var _testing = false

func init() {
    if _testing {
        return
    }

    var err error // Necessary to prevent config variable shadowing
    config, err = loadConfig("./client/config.yml")
    if err != nil {
        log.Fatal(err)
    }
}

// ...
Run Code Online (Sandbox Code Playgroud)

在测试文件中,您可以执行以下操作:

// not nice but works
var _ = (func() interface{} {
    _testing = true
    return nil
}())

func TestNew(t *testing.T) {
    expected := &Config{}
    observed := New()
    if !reflect.DeepEqual(observed, expected) {
        t.Errorf("observed %+v. expecting %+v\n", observed, expected)
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在此处阅读有关初始化顺序的更多信息:https : //golang.org/ref/spec#Program_initialization_and_execution

  • 感谢您的回答。我决定不使用`init()`。在 `New` 函数中调用 `loadConfig` 并在该函数中返回一个错误似乎更合适。 (2认同)
  • 在某些情况下,我使用它来测试 GCP 云功能。由于我的函数的全局依赖项是在 func init() 中初始化的,通过这种方法,我可以首先在测试文件中模拟它们,对实际代码的唯一更改是检查 deps 是否已经初始化,如果是,则跳过真正的初始化。如果有人有更好或更“正确”的方法,我会洗耳恭听 (2认同)