【问题标题】:Issue with go package declaration containing more than 2 words separated by underscore包含两个以上用下划线分隔的单词的 go 包声明问题
【发布时间】:2020-08-09 08:21:54
【问题描述】:

大家,我对我所看到的感到困惑;我有以下tree

├── go.mod
├── main.go
└── server
    ├── server.go
    └── server_integration_test.go

假设我的模块名称 (mod.go) 是 gotestserver.go的内容:

package server

type MyStruct struct {
    Hello string
}

func (m MyStruct) SayHello() string {
    return m.Hello
}

server_integration_test.go的内容:

package server_integration_test

import (
    "testing"
)

func TestIntegration(t *testing.T) {
    t.Errorf("just gonna fail!")
}

最后是我的main.go`:

package main

import (
    "fmt"
    "gotest/server"
)

func main() {
    my := server.MyStruct{Hello: "my-struct"}
    fmt.Println("from mystruct", my.SayHello())
}

当我运行go build(或go test ./...)时,我收到以下错误:

main.go:5:2: found packages server (server.go) and server_integration (server_integration_test.go) in /tmp/gotest/server

但如果我将我的server_integration_test.go 更改为:

package server_test
// ...

一切正常。

谁能解释一下这里发生了什么?

【问题讨论】:

  • test packagesgo test 命令支持 _test.go 文件中的两个包名:目录中的包名和带有_test 后缀的目录中的包名。包名server_integration_test 失败,因为它不是serverserver_test
  • @CeriseLimón 将其写为答案而不是评论

标签: go go-modules go-packages go-testing


【解决方案1】:

server 包测试支持的包名称为 serverserver_test

test packages:

'Go test' 重新编译每个包以及名称与文件模式“*_test.go”匹配的所有文件。这些附加文件可以包含测试函数、基准函数和示例函数。 ...

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

_test 后缀应用于被测包的名称(可以改进文档以使这一事实更加明确)。

【讨论】:

  • 谢谢 Cerise,我尝试从您提供的链接中查找信息,但无法找到。您介意从那里添加报价或其他内容吗?
猜你喜欢
  • 1970-01-01
  • 2018-03-24
  • 2016-05-15
  • 2015-03-02
  • 2021-02-19
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 2012-02-26
相关资源
最近更新 更多