Is it possible to have a shared context across unit tests in go test?

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

Is it possible to have a shared context across unit tests in go test?

问题

我正在使用Go语言实现一个trie树,以此来学习这门语言。我想从一开始就编写测试,以了解Go语言的处理方式。

在测试trie树时,我遇到的一个问题是每次单元测试都需要重新构建trie树。有没有办法在单元测试之间重用同一个trie树的实例?理想情况下,我希望能够在没有任何外部依赖的情况下实现这一点。

英文:

I am implementing a trie in Go as a way of learning the language. I want to write tests from the get go as a way of getting a feel for Go's approach to things.

One problem I am having when testing my trie is that I have to rebuild it for every unit test. Is there a way to reuse the same instantiation of my trie across unit tests? Ideally, I'd like a way to do this without any external dependencies.

答案1

得分: 4

是的:只需在您的trie_test.go中的func init()中构建它即可。(甚至可以使用字面量。)

英文:

Yes: Just construct it in func init() in your trie_test.go. (Or even use a literal.)

答案2

得分: 3

如果您不介意额外的依赖,gocheck包提供了将测试分组为套件的功能。然后,您可以定义SetUpSuiteTearDownSuite方法来执行该套件中的测试共享的任何资源的初始化和清理操作。

英文:

If you don't mind the extra dependency, the gocheck package provides the ability to group tests into suites. You can then define SetUpSuite and TearDownSuite methods to perform initialisation and tear down of any resources shared by the tests in that suite.

huangapple
  • 本文由 发表于 2014年2月7日 08:13:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/21616853.html
匿名

发表评论

匿名网友

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

确定