Golang Mocking - 类型冲突问题

Golang Mocking - problems with type collision

我正在模拟一个 DataStore,它具有 Get/Set 功能。我遇到的问题是:不能在 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 和您的模拟商店实现的接口。
  • 使用上述接口作为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)