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)
}
使用猴子补丁:
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 关注
- 175 浏览
添加回答
举报