简体   繁体   English

所有测试的 Golang 全局设置(在相同和其他子模块中)。

[英]Golang global setup for all tests (within same and other sub modules).

I generally try to run the command go test ./... for CI/CD pipeline which used to run all test cases among all the subdirectories.我通常尝试为 CI/CD 管道运行命令go test ./... ,该管道用于在所有子目录中运行所有测试用例。

But I recently refactored my code to take config file path from flag parsing and then reading and initializing all variables(required before server startup).This change required to remove all initialization code from init function -> custom function which will be called from main.但是我最近重构了我的代码,以从标志解析中获取配置文件路径,然后读取和初始化所有变量(在服务器启动之前需要)。此更改需要从init function -> custom function

Now everything relates is done but all test cases are not working as I need to call all the custom functions from somewhere.现在一切都完成了,但所有测试用例都不起作用,因为我需要从某个地方调用所有自定义函数。

I tried using the TestMain feature but I think it is only working for the same module and all test cases are failing.我尝试使用 TestMain 功能,但我认为它只适用于同一个模块并且所有测试用例都失败了。

func TestMain(m *testing.M) { 
    mySetupFunction()
    retCode := m.Run()
    myTeardownFunction()
    os.Exit(retCode)
}

Need help to know how can I create a global test setup or would like to know is there any other better way for above-mentioned refactoring.需要帮助以了解如何创建全局测试设置,或者想知道上述重构是否有其他更好的方法。

I have my modules structure as follow我的模块结构如下

A
    B
    C
    D
        E
            F
        G
            H
    I
main.go 

where parent module is A which contains main.go and various others module some nested to the deep level and all of them are having their own test cases其中父模块是 A ,其中包含 main.go 和其他各种模块,其中一些嵌套在深层,它们都有自己的测试用例

If you came from an init function, you could always make a test package that has the init code you'd like to run for your unit tests, and import that for the side effect.如果你来自一个init函数,你总是可以创建一个测试包,其中包含你想为你的单元测试运行的init代码,并导入它以获得副作用。

Make pkg called initializetest , implement the init() function, then in all your test files, import it like so:使 pkg 称为initializetest ,实现init()函数,然后在所有测试文件中,像这样导入它:

import (
  _ "project/path/initializetest"
)

I don't totally like this, as init() side effects can be a pain to debug.我不完全喜欢这样,因为 init() 副作用可能很难调试。 Calling the setup explicitly for each unit test would be better.为每个单元测试显式调用设置会更好。

Look at this .看看这个 I believe what you are looking for is func TestMain(m *testing.M) .我相信您正在寻找的是func TestMain(m *testing.M)

It is basically setup/teardown method.它基本上是设置/拆卸方法。 Go executes the tests "within" that that method. Go 在该方法的“内部”执行测试。 So you just need to set it up.所以你只需要设置它。 You don't have to call it in you tests.您不必在测试中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM