英文:
How can I share setup and teardown methods across packages when testing Go?
问题
假设我有两个包foo
和bar
。每个包都有一个文件和一个测试文件:
foo
---widget.go
---widget_test.go
bar
---wingding.go
---wingding_test.go
现在对于这两个测试文件(widget_test.go和wingding_test.go),我想共享一些设置代码。我知道我可以将这些代码放在每个包的main_test.go文件中。但显然我不想在两个地方复制/粘贴代码。那么我应该把这些代码放在哪里,以便在多个包之间共享?
英文:
Let's say I have two packages foo
and bar
. Each package has file and a test file:
foo
---widget.go
---widget_test.go
bar
---wingding.go
---wingding_test.go
Now for both tests (widget_test.go and wingding_test.go) I want to share some setup code. I know I can put this code inside each package inside main_test.go. But I obviously don't want to copy/paste code in two places. So where can I put this code so that it's shared across packages?
答案1
得分: 1
将其放入另一个名为baz
的包中,foo
和bar
在其测试中都要导入该包。我们在测试中使用这个包来进行数据库的设置和清理工作。
英文:
Put it in another package baz
that both foo
and bar
import in their tests. We use this for database setup and teardown code in our tests.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论