go测试结果在go:notfindmainmodule,butfound.git/configin/Users/dp/Documents

我刚刚开始使用 Golang,正在尝试运行单元测试。运行 go test 时,我最终从终端获得以下输出

go: cannot find main module, but found .git/config in /Users/dp/Documents
    to create a module there, run:
    cd ../.. && go mod init

我的文件结构比较简单,如下

??? CARDS
?   ??? .vscode
?   ??? main.go
?   ??? test.go
?   ??? deck_test.go
?   ??? my_cards.txt

Deck_test.go 的内容是

package main

import "testing"

func TestNewDeck(t *testing.T) {
    d := newDeck()

    if len(d) != 52 {
        t.Errorf("Length is not 52, got %v", len(d))
    }

    if d[0] != "A of D" {
        t.Errorf("First card is not A of D, got %v", d[0])
    }

    if d[len(d)-1] != "K of C" {
        t.Errorf("Last card is not K of C, got %v", d[len(d)-1])
    }

}

任何见解都会有所帮助!

回答

虽然不是必需的,但通常建议init您在 Git(或其他 VCS)存储库中时,以便模块可以依靠您remote的信息来正确确定模块的名称,例如:

git init
git remote add origin https://github.com/syntaqx/dacode
go mod init

允许go mod了解我的模块名称可能是github.com/syntaqx/dacode.

或者,我经常这样做是为了不需要以任何特定的顺序做事,你可以指定模块名称:

go mod init dacode # valid, but..
go mod init github.com/syntaqx/dacode # is generally better, because it describes my remote

通过指定它,模块可以在我所在的任何目录中初始化,而无需从代码中进行任何魔法。

注意:特别是当您刚开始时,我强烈建议您将模块命名为与用于存储库的命名结构相同的命名结构。通过这样做,您允许使用以下命令:

go get github.com/syntaqx/dacode

无需自己进行任何内部操作即可正常运行。当您更多地了解它们的工作方式时,您可以决定是要保持该约定还是违背常规,但保持一致可能更明智。

希望这有帮助!


回答

I am not using go modules (I know, I should). I got this error after upgrading from older Go versions to 1.16. From release notes:

Note that Go 1.16 requires use of Go modules by default, now that, according to our 2020 Go Developer Survey, 96% of Go developers have made the switch. We recently added official documentation for developing and publishing modules.

To still allow working as before, change it to as it was before. Add this in your .bashrc:

export GO111MODULE=auto


以上是go测试结果在go:notfindmainmodule,butfound.git/configin/Users/dp/Documents的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>