简体   繁体   中英

Error Message : go: go.mod file not found in current directory or any parent directory;

I am trying to run a unit test using go. The functions work properly in the main file. The function is given below:

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

}

But when I am running the unit test,

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)
        }
    }
}

I am getting this error ` Running tool: /usr/local/go/bin/go test -timeout 30s -run ^TestLoadLexicon$

go: go.mod file not found in current directory or any parent directory; see 'go help modules'

Test run finished at 29/08/2022, 02:58:53 < `

You need to add a go.mod file to your project's root directory.

Use modules to manage dependencies. Official docs: https://go.dev/blog/using-go-modules

Example:

go mod init project-name


go mod init example.com/project-name


go mod init github.com/you-user-name/project-name

You may need to use the tidy command to clean up after running one of the above commands.

go mod tidy

Use the path format from above when importing a package into your go file

Example:

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"
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM