Golang处理错误的包名

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

Golang processing wrong package names

问题

我有一个名为view_test的目录,里面有两个文件:main_test.gotest.go

这两个文件都以以下内容开头:

main_test.go:

package view_test

import (

test.go:

package view_test

import (

现在当我尝试使用go test进行测试时,我得到以下错误信息:

> 在/foo/internal/resources/view_test中找到了view (main_test.go)和view_test (test.go)这两个包

看起来有一些未知的假设导致go将包名混在一起。有人能告诉我这些假设是什么吗?

英文:

I have a directory view_test with two files: main_test.go and test.go.

Both files start with

main_test.go:

package view_test

import (

test.go:

package view_test

import (

Now when I try to test with go test I get:

> found packages view (main_test.go) and view_test (test.go) in /foo/internal/resources/view_test

Seems like there are some unknown assumptions where go starts clobbering together package names. Could someone enlighten me what these are?

答案1

得分: 3

在测试文件中,_test后缀是特殊的。根据go help test的说明:

> 声明了一个带有后缀“_test”的包的测试文件将被编译为一个单独的包,然后与主测试二进制文件链接并运行。

这个特性存在的目的是为了强制进行黑盒测试。通常,测试是在与非测试代码相同的包中定义的,因此测试可以访问未导出的标识符。如果不希望如此(例如,因为您希望确保测试只使用公共API),可以将测试声明在*_test包中。这是一个例外,即目录中的所有go文件必须声明相同的包名的规则。

正如在您的情况中的评论中指出的那样,这会导致在测试环境中命名为“view”的包和在生产代码环境中命名为“view_test”的包。这是错误的方式,因此在同一目录中会导致多个定义的包。

为了解决这个问题,请不要在生产代码中使用_test后缀。

英文:

The _test suffix in test files is special. From go help test:

> 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.

This feature exists so you can enforce black box tests. Normally tests are defined in the same package as non-test code, so tests have access to unexported identifiers. If that's not desired (i.e. because you want to make sure that tests only use the public API), tests can be declared in a *_test package instead. It's an exception to the rule that all go files in a directory must declare the same package name.

As pointed out in the comments in your case this leads to a package named "view" in the context of tests, and a package named "view_test " in the context of production code. That's the wrong way around and therefore causes multiple defined packages in the same directory.

Don't use the _test suffix for production code to fix the issue.

huangapple
  • 本文由 发表于 2021年11月30日 22:01:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/70170613.html
匿名

发表评论

匿名网友

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

确定