英文:
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包提供了将测试分组为套件的功能。然后,您可以定义SetUpSuite
和TearDownSuite
方法来执行该套件中的测试共享的任何资源的初始化和清理操作。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论