登录
首页 >  Golang >  Go问答

解决Golang测试包循环依赖的方法

来源:stackoverflow

时间:2024-02-16 20:51:22 470浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《解决Golang测试包循环依赖的方法》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

假设我有两个软件包,foobar(因此,foo.gofoo_test.gobar.gobar_test.go。) bar 依赖于 foo。在 bar_test.go 中,我想使用 foo_test.go 中定义的一些伪造类型。但由于不允许 *_test.go 文件导出类型,因此我将它们移至 foo 的测试包中,即 footestfoobar 都依赖该测试包。

假设 foo.go 有一些这样的接口:

type a interface {
   afunc() err
}

type b interface {
   bfunc() (a, error)
}

footest.go 中,我想用 fakes 实现这些接口:

type FakeA struct {}

type FakeB struct {}

func (fa *FakeA) AFunc() error {
   // this does something
}

func (fb *FakeB) BFunc() (A, error) {
   // this does something and returns an instance of A
}

这不起作用,因为它会创建循环依赖。 foo 依赖于 footest,但 footest 也需要依赖于 foo 才能引用 a

我是否缺少某种可以避免此问题的最佳实践?我的印象是,当测试文件需要在其他包中使用伪造的类型时,创建像 footest 这样的测试包是标准做法,但如果有更好的方法,我希望得到纠正。


正确答案


只要您在 foo_test.go 文件中使用 package foo_test,包 foo 就不会依赖于包 footest。在这种情况下,foo_test 将被编译为单独的包。但是,您无法访问 package foo 中的非导出类型。

例如

foo.go

package foo

type a interface {
   afunc() err
}

type b interface {
   bfunc() (a, error)
}

foo_test.go

package foo_test

// Add tests after importing package footest and foo

Read this answer 了解有关包命名的更多详细信息。

以上就是《解决Golang测试包循环依赖的方法》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>