3 回答

TA貢獻1765條經驗 獲得超5個贊
在這種情況下,Inc
中的方法DemoStruct
調用l.Validate
l 是 a的方法DemoStruct
。該方法的接收者明確地是一個DemoStruct
. 所以MockDemoStruct.Validate
不會調用該方法。
Go 沒有您在代碼中假設的繼承。您不能覆蓋DemoStruct
. MockDemoStruct
組成DemoStruct
. _ 為了實際測試這個方法,我建議傳遞DemoStruct
一個 db 接口,它可以在你的測試中被模擬。

TA貢獻1946條經驗 獲得超3個贊
為了使該方法可模擬,我們將不得不使用基于 DI(依賴注入)的代碼模式。
**We can mock only those methods which are injectable**.
我們有兩個選項可以在此代碼中引入依賴注入。
在界面的幫助下使用委托設計模式
使用函數作為類型引入 Monkey 修補
使用接口委托:
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)
}
使用猴子補?。?/p>
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)
}
- 3 回答
- 0 關注
- 166 瀏覽
添加回答
舉報