Sharing setup and teardown methods across packages is a common problem when testing Go. PHP editor Yuzai will answer this question for you. In Go language, you can use the `flag` package to set and get command line parameters. By using the `flag.Parse()` function in the test file, the command line parameters can be parsed and set into the corresponding variables. For test scenarios that require shared settings, global variables can be set in the test file and used in each test function. When the test is completed, you can disassemble it in the `TestMain` function and restore the original setting state. This enables shared setup and teardown methods across packages.
Suppose I have two packages foo
and bar
. Each package has a file and a test file:
foo ---widget.go ---widget_test.go bar ---wingding.go ---wingding_test.go
Now for these two tests (widget_test.go and wingding_test.go), I want to share some setup code. I know I can put this code into every package inside main_test.go. But I obviously don't want to copy/paste the code in two places. So where can I put this code so it can be shared between packages?
Put it into another package foo
and bar
imported in the test baz
. We use this for database setup and teardown code in our tests.
The above is the detailed content of How to share setup and teardown methods across packages when testing Go?. For more information, please follow other related articles on the PHP Chinese website!