可以将测试文件放在子文件夹中吗?

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

is it possible to place test files in subfolder

问题

当我将模块和其测试放在同一个目录中时,它可以正常工作。

  • module1.go
  • module1_test.go

但是当文件和测试文件的数量增加时,很难在代码中进行导航。

是否可以将Go测试放置在子文件夹中以获得更清晰的代码结构?
当我尝试这样做时,我遇到了命名空间错误。

我将文件module1_test.go放置在文件夹./test中。

  • module1.go
  • test/module1_test.go

现在我在测试中遇到了错误:

test/module1_test.go:8: undefined: someFunc

我的module1.go代码:

package package1

func someFunc() {

}

我的module1_test.go代码:

package package1

import (
"testing"
)

func TestsomeFunc(t *testing.T) {
someFunc()
}

英文:

When I have module and its test in the same directory it works ok.

- module1.go
- module1_test.go

But when number of files and test files grows it is hard to navigate through code.

Is it possible to place go tests to subfolder for cleaner code structure?
When I try to do it I got namespace error.

I placed file module1_test.go to folder ./test

- module1.go
- test/module1_test.go

Now I got error on testing:

test/module1_test.go:8: undefined: someFunc

My module1.go code:

package package1

func someFunc() {

}

My module1_test.go code:

package package1

import (
	"testing"
)

func TestsomeFunc(t *testing.T) {
	someFunc()
}

答案1

得分: 4

你可以将测试放在另一个目录中,但这不是常见的做法。你的测试需要导入被测试的包,并且无法访问未导出的方法。以下是一个示例:

文件 $GOPATH/src/somepath/package1/module1.go

package package1

func SomeFunc() {

}

文件 $GOPATH/src/somepath/package1/test/module1_test.go

package test

import (
	"testing"
	"somepath/package1"
)

func TestSomeFunc(t *testing.T) {
	package1.SomeFunc()
}

一些注意事项:

  • 我将SomeFunc方法改为导出方法,以便测试可以访问它。
  • 测试文件导入了被测试的包"somepath/package1"。
英文:

You can put the tests in another directory, but it is not common practice. Your tests will need to import the subject package and will not have access unexported methods in the subject package. This will work:

File $GOPATH/src/somepath/package1/module1.go

package package1

func SomeFunc() {

}

File $GOPATH/src/somepath/package1/test/module1_test.go

package test

import (
	"testing"
    "somepath/package1"
)

func TestSomeFunc(t *testing.T) {
	package1.SomeFunc()
}

A couple of notes:

  • I changed SomeFunc to an exported method so that the test can access it.
  • The test imports the subject package "somepath/package1"

huangapple
  • 本文由 发表于 2014年12月15日 11:26:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/27476932.html
  • go

Go模板:如何将array[]string打印到 :?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定