从*_test包中访问函数

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

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.

huangapple
  • 本文由 发表于 2014年8月29日 20:17:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/25568129.html
匿名

发表评论

匿名网友

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

确定