由於內置的testing
包,GO中的編寫單元測試很簡單。這是編寫單元測試的分步方法:
foo.go
的源文件,在同一軟件包中創建一個名為foo_test.go
的測試文件。寫測試函數:inside foo_test.go
,寫下從Test
開始的功能,然後是要測試的函數的名稱。這些函數採用*testing.T
參數。例如:
<code class="go">func TestFoo(t *testing.T) { // Test code here }</code>
斷言:使用t.Error
或t.Errorf
記錄錯誤並使測試失敗。如果重要的事情失敗,則可以使用t.Fatal
或t.Fatalf
立即停止測試。
<code class="go">if result != expected { t.Errorf("expected %v, but got %v", expected, result) }</code>
go test
命令執行測試。go test -cover
。表驅動的測試:使用表驅動的方法來減少代碼重複並有效測試多個方案。
<code class="go">func TestFoo(t *testing.T) { tests := []struct { input int expected int }{ {1, 2}, {2, 4}, {-1, -2}, } for _, tt := range tests { result := foo(tt.input) if result != tt.expected { t.Errorf("foo(%d) = %d, want %d", tt.input, result, tt.expected) } } }</code>
遵守GO編寫單元測試的最佳實踐可以顯著提高測試的質量和可維護性。以下是一些關鍵實踐:
TestFooReturnsDoubleOfInput
比TestFoo
更具描述性。並行測試:使用t.Parallel()
並行運行測試,這可以顯著加快您的測試套件,尤其是對於大型項目。
<code class="go">func TestFoo(t *testing.T) { t.Parallel() // Test code here }</code>
在GO中進行嘲笑可以通過用受控的假物體替換其依賴項來幫助隔離測試的單元。這是您可以使用模擬來增強單元測試的方法:
選擇一個模擬庫:流行的GO模擬庫包括GoMock
, testify/mock
和gomock
。例如,用testify/mock
:
<code class="go">import ( "testing" "github.com/stretchr/testify/mock" ) type MockDependency struct { mock.Mock } func (m *MockDependency) SomeMethod(input string) string { args := m.Called(input) return args.String(0) }</code>
設置期望:在執行測試的函數之前,請使用庫的API設置模擬的預期行為。
<code class="go">mockDependency := new(MockDependency) mockDependency.On("SomeMethod", "input").Return("output")</code>
斷言模擬呼叫:測試後,驗證該模擬是否按預期撥打。
<code class="go">mockDependency.AssertCalled(t, "SomeMethod", "input")</code>
幾種工具可以幫助您有效地管理和運行單元測試。這是一些受歡迎的清單:
go test
命令用途廣泛,可以與各種標誌一起使用以自定義測試執行。例如, go test -v
go test -coverprofile=coverage.out
生成覆蓋範圍報告。Gomega
一起用於比賽和斷言。require
, assert
流利的主張,測試組織suite
以及模擬依賴的mock
。組合使用這些工具可以幫助簡化測試過程,改善測試覆蓋範圍並使您的測試套件更加可維護和高效。
以上是您如何在GO中編寫單元測試?的詳細內容。更多資訊請關注PHP中文網其他相關文章!