go單元測試
1.使用testing框架 :
1.1. go test : 如果執行正確,無日誌. 錯誤時,會輸出日誌
1.2. go test -v : 執行正確或錯誤都會輸出日誌
1.3. 當出現錯誤時,可以使用t.fatalf 來格式化輸出錯誤資訊,並退出日誌
1.4. t.logf 方法可以輸出相應的日誌
1.5. 測試用例函式沒有放在main函式中也可執行,這是testing框架的功能
1.6. pass表示測試用例執行成功,fail表示測試用例執行失敗
1.7. 測試單個檔案要帶上被測試的原始檔: go test -v cal_test.go cal.go
1.8. 測試單個方法: go test -v -test.run testaddupper
testing框架執行步驟:
1.將以***_test.go的檔案引入
import
...
2.呼叫test***( )函式 (呼叫所有以test開頭的函式)
main()
注:測試函式test後面字母必須大寫
2.例項
例項11.被測試函式
package cal
//被測試函式
func
addupper
(n int
)int
return res
}
2.測試函式
//cal_test.go
package cal
import
("testing"
//引入go的testing框架包
)//編寫測試用例
func
testaddupper
(t *testing.t)
//如果正確,輸入日誌
t.logf
("addupper(10) 執行正確..."
)}
例項2
1.被測試函式
package monster
import
("encoding/json"
"io/ioutil"
"fmt"
)type monster struct
//給monster繫結方法, 可以講乙個monstar變數(物件), 序列化後儲存在檔案中
func
(this *monster)
store()
bool
//儲存到檔案
filepath :=
"/users/lx/documents/git_projects/github/gofile/src/testing/monster.ser"
ioutil.
writefile
(filepath, data,
0666
)if err !=
nilreturn
true
}//給monster繫結方法restore, 可以將乙個序列化的monster從檔案中讀取
func
(this *monster)
restore()
bool
//2.使用讀取到的data, 反序列化
err = json.
unmarshal
(data, this)
if err !=
nilreturn
true
}
2.測試函式
//monster_test.go
package monster
import
("testing"
)//測試用例,測試 store 方法
func
teststore
(t *testing.t)
res := monster.
store()
if!res
t.logf
("monster.store() 測試成功!")}
//測試用例,測試 restore 方法
func
testrestore
(t *testing.t)
if monster.name !=
"紅孩兒"
t.logf
("monster.store() 測試成功!"
)}
go單元測試
go本身提供了一套輕量級的測試框架。mytest工程下有兩個檔案 main.go package main func main func add a,b int intmain test.go package main import testing func testadd1 t testing.t...
Go單元測試
對包含網路請求和響應的函式進行單元測試需要我們模擬客戶端請求和服務端返回。以乙個登入模組為例,main.go檔案如下 其中的重點是利用 http.newrequest構造乙個虛擬的http get請求,再用httptest.newrecorder 建立http.responesewriter,模擬真...
go 單元測試
先看乙個需求 在我們工作中,我們會遇到這樣的情況,就是去確認乙個函式,或者乙個模組的結果是否正確.傳統的方法 15.2.1 傳統的方式來進行測試 在 main 函式中,呼叫 addupper 函式,看看實際輸出的結果是否和預期的結果一致,如果一致,則說明函式正確,否則函式有錯誤,然後修改錯誤 不方便...