你可以從測試檔案外部呼叫測試函數嗎?
在 Go 中,單元測試通常使用 go test 運行,它識別並執行標記為的測試函數測試.T 參數。然而,問題出現了:可以從非測試檔案呼叫測試函數來啟動測試執行嗎?
答案:框架限制
不幸的是,答案是否定的。 Go 的測試框架旨在強制測試和非測試程式碼之間的分離。測試函數只能從測試文件中調用,並且被測試的單元必須從適當的套件中導入。
Go 中的測試模式
Go 支援兩種主要測試模式:
- 黑盒測試:測試從包外部導出的函數,模擬其他包如何與它們互動。
- 白盒測試: 從包內測試未導出的函數,提供對內部實作細節的存取。
將其付諸實踐
考慮一個名為 example 的範例包,其中包含 add 實用函數和導出的 Sum利用內部 add 函數的函數。
example.go:包含匯出和未匯出函數的軟體包
<code class="go">package example func Sum(nums ...int) int { sum := 0 for _, num := range nums { sum = add(sum, num) } return sum } func add(a, b int) int { return a + b }</code>
example_test.go 中的黑盒測試
<code class="go">package example_test import ( "testing" "example" ) func TestSum(t *testing.T) { tests := []struct { nums []int sum int }{ {nums: []int{1, 2, 3}, sum: 6}, {nums: []int{2, 3, 4}, sum: 9}, } for _, test := range tests { s := example.Sum(test.nums...) if s != test.sum { t.FailNow() } } }</code>
<code class="go">package example import "testing" func TestAdd(t *testing.T) { tests := []struct { a int b int sum int }{ {a: 1, b: 2, sum: 3}, {a: 3, b: 4, sum: 7}, } for _, test := range tests { s := add(test.a, test.b) if s != test.sum { t.FailNow() } } }</code>總之,由於測試程式碼和非測試程式碼之間的設計分離,從測試檔案外部呼叫測試函數是不可能的在圍棋中。單元測試應始終透過 go test 指令執行,確保關注點分離並防止意外的程式碼執行。
以上是你可以在 Go 中從測試檔案外部呼叫測試函數嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Golang更適合高並發任務,而Python在靈活性上更有優勢。 1.Golang通過goroutine和channel高效處理並發。 2.Python依賴threading和asyncio,受GIL影響,但提供多種並發方式。選擇應基於具體需求。

Golang和C 在性能上的差異主要體現在內存管理、編譯優化和運行時效率等方面。 1)Golang的垃圾回收機制方便但可能影響性能,2)C 的手動內存管理和編譯器優化在遞歸計算中表現更為高效。

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。Golang以其并发模型和高效性能著称,Python则以简洁语法和丰富库生态系统著称。

Golang和Python分別在哪些方面更易用和學習曲線更平緩? Golang更適合高並發和高性能需求,學習曲線對有C語言背景的開發者較平緩。 Python更適合數據科學和快速原型設計,學習曲線對初學者非常平緩。

Golang和C 在性能競賽中的表現各有優勢:1)Golang適合高並發和快速開發,2)C 提供更高性能和細粒度控制。選擇應基於項目需求和團隊技術棧。

Golang適合快速開發和並發編程,而C 更適合需要極致性能和底層控制的項目。 1)Golang的並發模型通過goroutine和channel簡化並發編程。 2)C 的模板編程提供泛型代碼和性能優化。 3)Golang的垃圾回收方便但可能影響性能,C 的內存管理複雜但控制精細。

goimpactsdevelopmentpositationality throughspeed,效率和模擬性。 1)速度:gocompilesquicklyandrunseff,IdealforlargeProjects.2)效率:效率:ITScomprehenSevestAndardArdardArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增強的Depleflovelmentimency.3)簡單性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

禪工作室 13.0.1
強大的PHP整合開發環境

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

Dreamweaver CS6
視覺化網頁開發工具