包名不匹配

Package name missmatch

我正在做一个项目,我在其中创建了附加结构。

tests->gchat_test下我有两个文件init.gogchat_test.go

//init.go
package gchat_test

//initiation code

//gchat_test.go
package gchat_test

//testing code

对于这些文件,我在 VSCode

中遇到以下错误

found packages gchat (gchat_test.go) and gchat_test (init.go) in /home/<<>>/errornotifier/tests/gchat_test

我也从控制台尝试过,只是为了确保这不是 VSCode 问题

~/Loans/errornotifier/tests/gchat (feture/initial)$ go test
found packages gchat (gchat_test.go) and gchat_test (init.go) in /home/<<>>/errornotifier/tests/gchat_test

我对另一组测试有类似的结构,但我没有遇到这个错误

tests->kafka_test下我有两个文件init.gokafka_test.go

//init.go
package kafka_test

//initiation code

//kafka_test.go
package kafka_test

//testing code

作为快速修复,我将启动从 tests->gchat_test->init.go 移到了 tests->gchat_test->gchat_test.go 并删除了 init.go 然后就可以了。

我想了解为什么会抛出此错误,即使我对这些文件具有相同的包名以及如何修复它

没有_test.go 后缀的文件将构成包的源文件。具有 _test.go 后缀的文件被 go build 排除。声明带有 _test 后缀的包的测试文件形成不同的包。

所以基本上你有一个普通gchat_test由non-test文件init.go定义,你有一个testgchat_test 由测试文件 gchat_test.go 定义。这是否有效取决于 Go 工具的实现。

总而言之,具有_test的包名称不应在non-test包中使用。 init.go是一个non-test 文件,它不应该声明测试包。

Compile packages and dependencies:

When compiling packages, build ignores files that end in '_test.go'.


Test packages:

'Go test' recompiles each package along with any files with names matching the file pattern "*_test.go". These additional files can contain test functions, benchmark functions, fuzz tests and example functions. See 'go help testfunc' for more. Each listed package causes the execution of a separate test binary. Files whose names begin with "_" (including "_test.go") or "." are ignored.

Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary.