我试图在测试用例中模拟一个结构方法,但它不起作用。我想在这里模拟Validate方法:`
package main
import (
"fmt"
)
type DemoInterface interface {
Inc(int) (int, error)
Validate(int) error
}
type DemoStruct struct{}
func (l DemoStruct) Inc(num int) (int, error) {
err := l.Validate(num)
if err != nil {
return 0, err
}
num = num + 100
return num, nil
}
func (l DemoStruct) Validate(num int) error {// SOME DB LOGIC IS HERE WHICH I CAN NOT POST at Stackoverflow
if num > 100 {
return fmt.Errorf("INVALID NUM %v", num)
}
return nil
}
func main() {
s, err := DemoStruct{}.Inc(10)
if err != nil {
fmt.Println(err)
}
fmt.Println(s)
}
`
我的测试用例:
package main
import (
"fmt"
"testing"
)
const (
SUCCESS = "SUCCESS"
ERROR = "ERROR"
)
type MockDemoStruct struct {
DemoStruct
functionality string
}
func (m MockDemoStruct) Validate(num int) error {
switch m.functionality {
case SUCCESS:
return nil
case ERROR:
fmt.Errorf("MOCK ERROR %v", num)
}
return fmt.Errorf("MOCK ERROR %v", num)
}
func TestPath(t *testing.T) {
t.Run("ERROR", func(t *testing.T) {
ls := MockDemoStruct{DemoStruct{}, ERROR}
res, err := ls.Inc(110)
expected := fmt.Errorf("MOCK ERROR %v", 10)
if err != expected {
t.Errorf("NOT MATCH %v %v", err, expected)
//NOT MATCH INVALID NUM 110 MOCK ERROR 10
}
fmt.Println(res)
})
}
这里没有调用MockDemoStruct.Validate 。我从 Validate 得到INVALID NUM 110,但它应该是MOCK ERROR 110