我正在嘗試使用 go 運(yùn)行單元測試。這些函數(shù)在主文件中正常工作。函數(shù)如下:func LoadLexicon(lexiconPath string) (map[string]string, error) { m := make(map[string]string) lexiconPath = strings.TrimSuffix(lexiconPath, "\n") if lexiconPath == "nil" { m["COME"] = "k V m" m["WORDS"] = "w 3` d z" m["MECCA"] = "m E k @" return m, nil } readFile, err := os.Open(lexiconPath) if err != nil { fmt.Println(err) return m, err } fileScanner := bufio.NewScanner(readFile) fileScanner.Split(bufio.ScanLines) var fileLines []string for fileScanner.Scan() { fileLines = append(fileLines, fileScanner.Text()) } lex_words := make(map[string]string) for _, line := range fileLines { temp := strings.Split(line, "\t") lex_words[strings.ToUpper(temp[0])] = temp[1] } return lex_words, err}但是當(dāng)我運(yùn)行單元測試時,func TestLoadLexicon(t *testing.T) { tests := []struct { n string want string }{ {"COME", "k V m"}, {"WORDS", "w 3` d z"}, {"MECCA", "m E k @"}, } for _, tc := range tests { if got, _ := LoadLexicon("nil"); got[tc.n] != tc.want { t.Errorf("got %s, want %s", got[tc.n], tc.want) } }}我收到這個錯誤`運(yùn)行工具:/usr/local/go/bin/go test -timeout 30s -run ^TestLoadLexicon$go: 在當(dāng)前目錄或任何父目錄中找不到 go.mod 文件;查看“去幫助模塊”試運(yùn)行于 29/08/2022 02:58:53 < `
1 回答

BIG陽
TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個贊
您需要將go.mod文件添加到項(xiàng)目的根目錄。
使用模塊來管理依賴關(guān)系。官方文檔:https ://go.dev/blog/using-go-modules
例子:
go mod init project-name
go mod init example.com/project-name
go mod init github.com/you-user-name/project-name
在運(yùn)行上述命令之一后,您可能需要使用 tidy 命令進(jìn)行清理。
go mod tidy
將包導(dǎo)入 go 文件時使用上面的路徑格式
例子:
import (
// Import internal and external packages like this
"github.com/you-user-name/project-name/package-name"
// Import standard library packages the normal way
"testing"
"math/rand"
)
- 1 回答
- 0 關(guān)注
- 331 瀏覽
添加回答
舉報(bào)
0/150
提交
取消