Golang测试包循环依赖问题

jcg*_*ley 1 testing go

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

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

type A interface {
   AFunc() err
}

type B interface {
   BFunc() (A, error)
}
Run Code Online (Sandbox Code Playgroud)

在 中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
}
Run Code Online (Sandbox Code Playgroud)

这是行不通的,因为它会产生循环依赖。foo依赖footest,还footest需要依赖foo才能参考A

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

A.K*_*han 7

只要您在 foo_test.go 文件中使用, packagefoo就不会依赖于 package 。在这种情况下,foo_test 将被编译为单独的包。但是,您将无权访问.footestpackage foo_testpackage foo

例如

foo.go

package foo

type A interface {
   AFunc() err
}

type B interface {
   BFunc() (A, error)
}
Run Code Online (Sandbox Code Playgroud)

foo_test.go

package foo_test

// Add tests after importing package footest and foo
Run Code Online (Sandbox Code Playgroud)

阅读此答案以获取有关包命名的更多详细信息。