Home  >  Article  >  Backend Development  >  How to share setup and teardown methods across packages when testing Go?

How to share setup and teardown methods across packages when testing Go?

王林
王林forward
2024-02-15 09:50:071035browse

在测试 Go 时如何跨包共享设置和拆卸方法?

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.

Question content

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?

Workaround

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete