How can I mock an interface method twice in golang test? For example:
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
}
...
}
When I test func GetBookDetail()
, how can I mock Get(key string, data interface{}) error
twice? I try to do this but its failed:
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()
...
}
Got error in test something like this:
Diff:
0: PASS: (string=book) matched by func(string) bool
1: FAIL: (*Book=&{ }) not matched by func() bool [recovered]
panic:
Note: I use github.com/stretchr/testify