我在使用 VsCode 測試 Go 應用程序時遇到一些問題。這是我的 launch.json{ "name": "Test", "type": "go", "request": "launch", "mode": "test", "program": "${workspaceFolder}/test", "env": {}, "args": []}現在我遇到的問題是我的應用程序應該在子文件夾中寫入文件(atm 是 ./temp)。為此,我有兩個函數,第一個是確定文件路徑func getFilePath() string { dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { panic(err) } return dir + "/temp/ocicd-config.yaml"}另一個用于保存文件func SaveToYaml(Config Structs.Project) { fmt.Println("Saving Config") yaml, err := yaml.Marshal(Config) if err != nil { panic(err) } fmt.Println(string(yaml)) ioutil.WriteFile(getFilePath(), yaml, 0644)}以及加載文件func Load() Structs.Project { fmt.Println("Loading Config") file, err := ioutil.ReadFile(getFilePath()) if err != nil { panic(err) } project := Structs.Project{} err = yaml.Unmarshal(file, &project) if err != nil { panic(err) } return project}現在的問題是,VsCode 使應用程序在 ./test 子文件夾中運行,這使我的應用程序嘗試從 ./test/temp 加載并保存到 ./test/temp,這不是我想要的。我嘗試更改我的 launch.json 以實際使用 ${workspace} 作為程序并使用“./test”作為參數,但這會使測試完全停止工作?,F在我很迷失。我有什么想法可以解決這個問題嗎?
1 回答

慕姐4208626
TA貢獻1852條經驗 獲得超7個贊
您應該在文件系統之上使用一個抽象層(而不是),而不是讓測試直接寫入磁盤上的文件(此模型可能會出現并發問題)ioutil
。
github.com/spf13/afero
是一個用于此目的的很棒的庫。對于您的測試用例,您可以簡單地傳遞 MemFs 層而不是 OsF。
- 1 回答
- 0 關注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消