Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

I generally try to run the command go test ./... for CI/CD pipeline which used to run all test cases among all the subdirectories.

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.

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.

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

like image 589
Abhishek Soni Avatar asked Nov 17 '22 09:11

Abhishek Soni


1 Answers

Look at this. I believe what you are looking for is func TestMain(m *testing.M).

It is basically setup/teardown method. Go executes the tests "within" that that method. So you just need to set it up. You don't have to call it in you tests.

like image 129
lsd Avatar answered Jun 27 '23 17:06

lsd