3 回答
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
在這種情況下,Inc中的方法DemoStruct調(diào)用l.Validatel 是 a的方法DemoStruct。該方法的接收者明確地是一個(gè)DemoStruct. 所以MockDemoStruct.Validate不會(huì)調(diào)用該方法。
Go 沒有您在代碼中假設(shè)的繼承。您不能覆蓋DemoStruct. MockDemoStruct組成DemoStruct. _ 為了實(shí)際測(cè)試這個(gè)方法,我建議傳遞DemoStruct一個(gè) db 接口,它可以在你的測(cè)試中被模擬。
TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
為了使該方法可模擬,我們將不得不使用基于 DI(依賴注入)的代碼模式。
**We can mock only those methods which are injectable**.
我們有兩個(gè)選項(xiàng)可以在此代碼中引入依賴注入。
在界面的幫助下使用委托設(shè)計(jì)模式
使用函數(shù)作為類型引入 Monkey 修補(bǔ)
使用接口委托:
type Deligation interface {
Validate(num int) error
}
type DemoStruct struct {
delegate Deligation
}
func (DemoStruct) Validate(num int) error {
if num > 100 {
return fmt.Errorf("INVALID NUM %v", num)
}
return nil
}
func (l DemoStruct) Inc(num int) (int, error) {
err := l.delegate.Validate(num) // Call method using delegate
if err != nil {
return 0, err
}
num = num + 100
return num, nil
}
func main() {
s, err := DemoStruct{delegate: DemoStruct{}}.Inc(10) // assign delegate inside DemoStruct
if err != nil {
fmt.Println(err)
}
fmt.Println(s)
}
使用猴子補(bǔ)丁:
func Validate(num int) error {
if num > 100 {
return fmt.Errorf("INVALID NUM %v", num)
}
return nil
}
type DemoStruct struct {
Validate func(num int) error // function as a type
}
func (l DemoStruct) Inc(num int) (int, error) {
err := l.Validate(num)// It can be replaced in test cases.
if err != nil {
return 0, err
}
num = num + 100
return num, nil
}
func main() {
s, err := DemoStruct{Validate: Validate}.Inc(10) // assign Validate inside DemoStruct
if err != nil {
fmt.Println(err)
}
fmt.Println(s)
}
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超2個(gè)贊
我認(rèn)為你還需要為'MockDemoStruct'實(shí)現(xiàn)'Inc'接收器,在這里你試圖過(guò)度使用結(jié)構(gòu)的繼承屬性,看起來(lái)GO不支持。
- 3 回答
- 0 關(guān)注
- 177 瀏覽
添加回答
舉報(bào)
