我在 中定義了main.go無法在main_test.go. 但是,在一些在線教程中,我看到函數是可訪問的:我想了解其中的區別,以及如何以慣用的方式構建這些函數。具體來說,我有一個包含多個二進制文件的應用程序:myapp/cmd/app/main.gomyapp/cmd/cli/main.gofunc main我目前在文件中運行了很多簡單的單元測試邏輯main.go。我只是在測試單個函數并讓它們打印輸出,如果我能避免的話,我不會試圖調用“測試”套件的全部功能。由于此時我在 main.go 頂部的測試太長了,我想將它們移動到特定的測試文件中,例如:myapp/cmd/app/main_test.gomyapp/cmd/cli/main_test.go這適用于我的 makefile:# Makefileall: test buildbuild: go build -o cmd/app/main cmd/app/main.go go build -o cmd/cli/main cmd/cli/main.gotest: go test ./cmd/app/main_test.go go test ./cmd/cli/main_test.go如果我只想運行我的測試文件,我想把這個項目放在我的app/main.go// cmd/app/main.gopackage mainfunc definedInMain(m string) string { // }func main() { m := definedInMain("1") fmt.Println(m) // all the rest of my app's logic...}并在我的main_test.go// cmd/app/main_test.gopackage main// no imports, I hope?func testDefinedInMain() { m := definedInMain("1") fmt.Println(m) }但是,這失敗了:undefined: definedInMainFAIL我很困惑,我必須將所有這些功能導入到我的main_test.go文件中(即使我嘗試,它也會建議"can't load package: ... myapp/cmd/app/main" in any of: ...")有沒有一種干凈、慣用的方法可以讓我在測試文件中測試我非常簡單的單元測試并在主文件中運行我的函數,而無需大量重寫導入或其他大量的重新架構?從某些鏈接中,我的印象是,如果我創建一個main_test.go,導入將自行進行(就像在這些示例中一樣)。https://medium.com/@thejasbabu/testing-in-golang-c378b351002d (其中反向函數未明確導入 reverse_test.go)https://tutorialedge.net/golang/intro-testing-in-go/ (其中 Calculate 函數未顯式導入 main_test.go)https://blog.alexellis.io/golang-writing-unit-tests/ (其中 Sum 函數未在 main_test.go 中顯式導入)所以,你可以看到我有點困惑教程免費導入它們的功能,而我沒有,我只是想更好地理解魔法。是不是我的函數 definedInMain 是私有的,因為它是小寫的?我確實希望這個函數是私有的,但我希望它能以與在 main.go 中可用的方式相同的方式導出到 main_test.go 文件。我是否必須完全公開才能在另一個文件中進行測試?這似乎不正確,例如,“只能在 go 中對公共方法進行單元測試嗎?”
- 0 回答
- 0 關注
- 105 瀏覽
添加回答
舉報
0/150
提交
取消