在测试Go时,如何在不同的包之间共享设置(setup)和拆卸(teardown)方法?

huangapple go评论94阅读模式
英文:

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

问题

假设我有两个包foobar。每个包都有一个文件和一个测试文件:

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的包中,foobar在其测试中都要导入该包。我们在测试中使用这个包来进行数据库的设置和清理工作。

英文:

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.

huangapple
  • 本文由 发表于 2017年1月28日 02:18:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/41900523.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定