英文:
Accessing function from *_test package
问题
我有一个名为pkg
的包。pkg
包的测试代码位于*_test.go
文件中。然而,为了初始化一个测试运行器,我需要从其他包中导入一个函数,但由于循环依赖的原因,我无法在pkg
中导入该函数。
我的想法是使用pkg_test
包。是否有办法在pkg_test
中访问pkg
中的测试函数(即*_test.go
文件中的函数)?
我的项目结构如下:
├── f.go # pkg包
├── f_test.go # pkg包
├── init_test.go # pkg_test包
换句话说:我想在init_test.go
中访问f_test.go
中的函数,或者反过来(在f_test.go
中访问init_test.go
中的函数)。有没有办法做到这一点?
PS:在f_test.go
中,我无法导入pkg_test
包。
英文:
I have a package pkg
. The test for package pkg
are in _test.go files. However to initialize a test runner I need a a function from other package which I can't import in pkg
because of circular dependecy.
My idea is to use pkg_test
package.
Is there any way to access test functions (in _test.go files) from pkg
in pkg_test
?
My project structure:
├── f.go # package pkg
├── f_test.go # package pkg
├── init_test.go # package pkg_test
In other words: I want to access a function from f_test.go in init_test.go or vice versa (access a function from init_test.go in f_test.go. Is there any way to do it?
PS: in f_test.go I can't import pkg_test
答案1
得分: 2
这是一个很好的机会,可以采取以下两种方式之一:
- 将函数从
pkg_test
移动到pkg
中 - 或者通过接口(例如模拟数据库)来模拟
pkg_test
中的函数操作,以避免依赖于初始化过程。
试图绕过这个限制是试图解决依赖问题而不是解决它。
话虽如此,如果你可以在pkg_test
中导入pkg
,那么是的,你可以在init_test.go
中访问f_test.go
中的函数。
英文:
This is generally a good opportunity to:
- either move the function from pkg_test in pkg
- or mock whatever the function from pkg_test is doing, in order to not rely on that initialization, through an interface (like mocking database)
Trying to go around that limitation is trying to work around the dependency issue rather than solving it.
That being said, if you can import pkg in pkg_test, then yes, you can access a function from f_test.go
in init_test.go
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论