1 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
我不會(huì)測(cè)試任何涉及 Gorilla 或任何其他 3rd 方包的東西。如果您想測(cè)試以確保它正常工作,我會(huì)為您的應(yīng)用程序運(yùn)行版本(例如 CI 服務(wù)器)的端點(diǎn)設(shè)置一些外部測(cè)試運(yùn)行程序或集成套件。
相反,單獨(dú)測(cè)試您的中間件和處理程序 - 就像您可以控制的那樣。
但是,如果您準(zhǔn)備測(cè)試堆棧(mux -> 處理程序 -> 處理程序 -> 處理程序 -> MyHandler),那么使用函數(shù)作為變量全局定義中間件可能會(huì)有所幫助:
var addCors = func(h http.Handler) http.Handler {
...
}
var checkAPIKey = func(h http.Handler) http.Handler {
...
}
在正常使用期間,它們的實(shí)現(xiàn)保持不變。
r.Handle("/documents", addCors(checkAPIKey(getDocuments(sendJSON)))).Methods("GET")
但是對(duì)于單元測(cè)試,您可以覆蓋它們:
// important to keep the same package name for
// your test file, so you can get to the private
// vars.
package main
import (
"testing"
)
func TestXYZHandler(t *testing.T) {
// save the state, so you can restore at the end
addCorsBefore := addCors
checkAPIKeyBefore := checkAPIKey
// override with whatever customization you want
addCors = func(h http.Handler) http.Handler {
return h
}
checkAPIKey = func(h http.Handler) http.Handler {
return h
}
// arrange, test, assert, etc.
//
// when done, be a good dev and restore the global state
addCors = addCorsBefore
checkAPIKey = checkAPIKeyBefore
}
如果您發(fā)現(xiàn)自己經(jīng)常復(fù)制粘貼此樣板代碼,請(qǐng)將其移至單元測(cè)試中的全局模式:
package main
import (
"testing"
)
var (
addCorsBefore = addCors
checkAPIKeyBefore = checkAPIKey
)
func clearMiddleware() {
addCors = func(h http.Handler) http.Handler {
return h
}
checkAPIKey = func(h http.Handler) http.Handler {
return h
}
}
func restoreMiddleware() {
addCors = addCorsBefore
checkAPIKey = checkAPIKeyBefore
}
func TestXYZHandler(t *testing.T) {
clearMiddleware()
// arrange, test, assert, etc.
//
restoreMiddleware()
}
關(guān)于單元測(cè)試端點(diǎn)的旁注......
由于中間件應(yīng)該以合理的默認(rèn)值運(yùn)行(預(yù)計(jì)正常傳遞,而不是您要在 func 中測(cè)試的底層數(shù)據(jù)流的互斥狀態(tài)),我建議在實(shí)際主 Handler 函數(shù)的上下文之外對(duì)中間件進(jìn)行單元測(cè)試。
這樣,您就有了一組嚴(yán)格針對(duì)中間件的單元測(cè)試。另一組測(cè)試完全專注于您正在調(diào)用的 url 的主要處理程序。它使新手更容易發(fā)現(xiàn)代碼。
- 1 回答
- 0 關(guān)注
- 170 瀏覽
添加回答
舉報(bào)