如何在golang测试中模拟两次接口(interface)方法?例如:
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()
...
}
在测试中遇到这样的错误:
Diff:
0: PASS: (string=book) matched by func(string) bool
1: FAIL: (*Book=&{ }) not matched by func() bool [recovered]
panic:
注意:我使用github.com/strethr/testify
最佳答案
首先,回答您的问题:是的,您可以指定要返回一个值与另一个值的次数。您可以使用 Once()
、Twice()
或 Times(n)
来实现,如下所示:
m.On("foo", ...).Return(...).Once()
此外,在测试结束时,您应该通过执行 m.AssertExpectations(t)
确认方法被调用的次数正确。
现在,我的建议是:您的模拟似乎过于复杂了。当您希望检查部分相等性或在检查相等性之前进行一些处理时,您只需使用 mock.MatchedBy
。在您的情况下,m.On("Get", "book", &Book{})...
应该可以正常工作。
此外,由于您对模拟函数有不同的“输入”——您不一定需要在末尾添加 Once()
。只有当你想返回不同的值但参数保持不变时,它才成为强制性的。但是,断言该函数是否被调用了预期的次数通常是一种很好的做法。
关于unit-testing - 使用 testify 使用不同的输入和输出模拟接口(interface)方法两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62165773/