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

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

王林
Release: 2024-02-15 09:50:07
forward
1060 people have browsed it

在测试 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
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template