如何在 golang 测试中模拟两次接口方法?例如:
type myCache interface{
Get(key string, data interface{}) error
}
type service struct {
cache myCache
}
func (s service) GetBookDetail() (BookDetail, error) {
...
book := Book{}
err := s.cache.Get("book", &book)
if err != nil {
return BookDetail{}, err
}
...
author := Author{}
err := s.cache.Get("author", &author)
if err != nil {
return BookDetail{}, err
}
...
}
当我测试时func GetBookDetail()
,我怎样才能模拟Get(key string, data interface{}) error
两次?我尝试这样做,但失败了:
func TestGetBookDetail(t *testing.T) {
...
mockCache.On("Get",
mock.MatchedBy(func(key string) bool {
return key == "book"
}), mock.MatchedBy(func(data interface{}) bool {
return data == &Book{}
})).Return(nil)
mockCache.On("Get",
mock.MatchedBy(func(key string) bool {
return key == "author"
}), mock.MatchedBy(func(data interface{}) bool {
return data == &Author{}
})).Return(nil)
...
out, err := mockService.GetBookDetail()
...
}
在测试中出现如下错误:
差异:
0: PASS: (string=book) 由 func(string) bool 匹配
1: FAIL: (*Book=&{ }) 不匹配 func() bool [恢复]
恐慌:
注意:我使用github.com/stretchr/testify