Golang模拟 – 类型冲突的问题

huangapple go评论85阅读模式
英文:

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 to EventHandler, as the Get 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)

huangapple
  • 本文由 发表于 2015年10月24日 02:11:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/33308887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定