1 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
如果您的代碼使用 const 值,則它不適合測(cè)試(關(guān)于使用該參數(shù)的不同值進(jìn)行測(cè)試)。
您可以通過(guò)輕微的重構(gòu)來(lái)解決您的問(wèn)題。假設(shè)您有一個(gè)使用此常量的函數(shù):
const baseUrl = "http://google.com"
func MyFunc() string {
// use baseUrl
}
您可以創(chuàng)建另一個(gè)將基本 URL 作為參數(shù)的函數(shù),并且您的原始函數(shù)MyFunc()調(diào)用它:
const baseUrl_ = "http://google.com"
func MyFunc() string {
// Call other function passing the const value
return myFuncImpl(baseUrl_)
}
func myFuncImpl(baseUrl string) string {
// use baseUrl
// Same implementation that was in your original MyFunc() function
}
這樣你的庫(kù)的 API 不會(huì)改變,但現(xiàn)在你可以MyFunc()通過(guò) testing 來(lái)測(cè)試你原來(lái)的功能myFuncImpl(),你可以傳遞任何值來(lái)測(cè)試。
調(diào)用MyFunc()將保持安全,因?yàn)樗偸菍?const 傳遞baseUrl_到myFuncImpl()實(shí)現(xiàn)現(xiàn)在所在的位置。是否myFuncImpl()導(dǎo)出此新函數(shù)由您決定;它可能保持未導(dǎo)出狀態(tài),因?yàn)闇y(cè)試代碼可能(應(yīng)該)放在同一個(gè)包中并且可以毫無(wú)問(wèn)題地調(diào)用它。
- 1 回答
- 0 關(guān)注
- 194 瀏覽
添加回答
舉報(bào)