我正在模拟一个 DataStore 及其获取/设置功能。我遇到的问题是:不能在 EventHandler 的参数中使用 s(类型 *MockStore)作为类型 *datastore.Storage
这是因为我的 EventHandler 函数需要传递一个 *datastore.Storage 作为参数类型。我想使用我创建的 MockStore 而不是真正的数据存储来测试(http 测试)EvenHandler()。我正在使用 golang testify 模拟包。
一些代码示例
type MockStore struct{
mock.Mock
}
func (s *MockStore) Get() ...
func EventHandler(w http.ResponseWriter, r *http.Request, bucket *datastore.Storage){
//Does HTTP stuff and stores things in a data store
// Need to mock out the data store get/sets
}
// Later in my Tests
ms := MockStore
EventHandler(w,r,ms)
最佳答案
一些事情:
- 创建一个将由
datastore.Storage
和您的模拟商店实现的接口(interface)。 - 使用上述接口(interface)作为
EventHandler
中的参数类型(not a pointer to the interface) . - 将指向您的
MockStore
的指针传递给EventHandler
,因为Get
方法是为指向该结构的指针定义的。
您更新后的代码应类似于以下内容:
type Store interface {
Get() (interface{}, bool) // change as needed
Set(interface{}) bool
}
type MockStore struct {
mock.Mock
}
func (s *MockStore) Get() ...
func EventHandler(w http.ResponseWriter, r *http.Request,bucket datastore.Storage){
//Does HTTP stuff and stores things in a data store
// Need to mock out the data store get/sets
}
// Later in my Tests
ms := &MockStore{}
EventHandler(w,r,ms)
关于unit-testing - Golang Mocking - 类型冲突问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33308887/