英文:
Golang Mocking - problems with type collision
问题
我正在模拟一个DataStore和它的Get/Set功能。我遇到的问题是:无法将s(类型为MockStore)作为参数传递给EventHandler函数中的datastore.Storage类型。
这是因为我的EventHandler函数需要传递一个*datastore.Storage类型的参数。我想使用我创建的MockStore来测试(使用http测试)EventHandler(),而不是真实的数据存储。我正在使用golang的testify mock包。
一些代码示例:
type MockStore struct{
mock.Mock
}
func (s *MockStore) Get() ...
func EventHandler(w http.ResponseWriter, r *http.Request, bucket *datastore.Storage){
//执行HTTP操作并将数据存储在数据存储中
//需要模拟数据存储的get/set操作
}
//稍后在我的测试中
ms := MockStore
EventHandler(w,r,ms)
英文:
I'm mocking out a DataStore and it's Get/Set functionality. The trouble I'm having is: cannot use s (type *MockStore) as type *datastore.Storage in argument to EventHandler
This is caused by my EventHandler function needing to be passed a *datastore.Storage as an argument type. I want to Test (http test) EvenHandler() using the MockStore I've created instead of the real datastore. I'm using the golang testify mock package.
Some Code Examples
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)
答案1
得分: 2
一些事情:
- 创建一个接口,该接口将由
datastore.Storage
和您的模拟存储实现。 - 将上述接口作为
EventHandler
的参数类型(而不是接口的指针)。 - 将指向您的
MockStore
的指针传递给EventHandler
,因为Get
方法是针对结构体指针定义的。
您的更新后的代码应该类似于以下内容:
type Store interface {
Get() (interface{}, bool) // 根据需要进行更改
Set(interface{}) bool
}
type MockStore struct {
mock.Mock
}
func (s *MockStore) Get() ...
func EventHandler(w http.ResponseWriter, r *http.Request, bucket datastore.Storage){
// 执行HTTP操作并将数据存储在数据存储中
// 需要模拟数据存储的获取/设置操作
}
// 稍后在我的测试中
ms := &MockStore{}
EventHandler(w, r, ms)
英文:
A few things:
- Create an interface that will be implemented both by
datastore.Storage
and your mock store. - Use the above interface as the argument type in
EventHandler
(not a pointer to the interface). - Pass a pointer to your
MockStore
toEventHandler
, as theGet
method is defined for a pointer to the struct.
Your updated code should be something like the following:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论