首页 > 解决方案 > 执行测试时找不到 Go 模块包

问题描述

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

这是我的 Go 模块的结构:

├── go.mod

├── gopher.json

├── main.go

├── story.go

├── 模板.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. 这是否意味着引用包的唯一方法(甚至在您的模块中)是通过远程 repo URL 引用它们,例如 github.com ...或者最终只是将包复制到 /usr/local/go/src (这一点都不友好)

标签: gotestingmodulepackage

解决方案


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


推荐阅读