执行测试时找不到 Go 模块包

Go module package not found when executing the tests

我知道我对 Go 是如何寻找一个包缺乏基本的了解,但让我强调一下我的想法,如果需要的话 - 你可以投反对票。

这是我的 Go 模块结构:

├── go.mod

├── gopher.json

├── main.go

├── story.go

├── template.html

└──测试

   ├── cyow_test.go
   └── gopher.json

除了应该放置测试的直接、专用的 /tests 目录之外,别无其他。

这是我的 cyow_test.go 文件:


import (
    "io/ioutil"
    "story"
    "testing"
)

func TestUnmarshallOverStoryStruct(t *testing.T) {
    t.Parallel()
    content, fileError := ioutil.ReadFile("gopher.json")
    if fileError != nil {
        t.Error("The file for Chapter is not found.")
    }

    story := story.Story{}
    fmt.Println("Story has been initialized")

    err := json.Unmarshal([]byte(content), &story)
    fmt.PRintln("Json unmarshall statement has been executed.")
    if err != nil {
        panic(err)
    }
}

这个功能可以忽略,主要是为了学习。重要的是我依赖于一个故事包,它已被声明为模块的一部分。

当我进入 /tests 并且 运行 'go test' 我收到:

cyow_test.go:5:2: package story is not in GOROOT (/usr/local/go/src/story)

我在模块根目录中有 运行 'go mod tidy',我的简单问题是:

  1. 为什么 Go 默认不查找包?它是模块的一个包的一部分,所以它应该是原生的 - 这是我的假设。
  2. 这是否意味着引用包(甚至在您的模块内部)的唯一方法是通过远程存储库引用它们 URL,例如 github.com ... 或者最终只是复制打包到/usr/local/go/src(一点都不友好)

你的假设是错误的。导入包的方式是'module/package'。模块名称不必包含存储库名称。不要复制包到源码目录。