duanguane1670 2019-06-26 12:07
浏览 81

在Go中模拟MongoDB响应

I'm fetching a document from MongoDB and passing it into function transform, e.g.

var doc map[string]interface{}
err := collection.FindOne(context.TODO(), filter).Decode(&doc) 
result := transform(doc)

I want to write unit tests for transform, but I'm not sure how to mock a response from MongoDB. Ideally I want to set something like this up:

func TestTransform(t *testing.T) {
    byt := []byte(`
    {"hello": "world",
     "message": "apple"}
 `)

    var doc map[string]interface{}

    >>> Some method here to Decode byt into doc like the code above <<<

    out := transform(doc)
    expected := ...
    if diff := deep.Equal(expected, out); diff != nil {
        t.Error(diff)
    }
}

One way would be to json.Unmarshal into doc, but this sometimes gives different results. For example, if the document in MongoDB has an array in it, then that array is decoded into doc as a bson.A type not []interface{} type.

  • 写回答

2条回答 默认 最新

  • doutuo1939 2019-06-26 13:18
    关注

    The best solution to write testable could would be to extract your code to a DAO or Data-Repository. You would define an interface which would return what you need. This way, you can just used a Mocked Version for testing.

    // repository.go
    type ISomeRepository interface {
        Get(string) (*SomeModel, error)
    }
    
    type SomeRepository struct { ... }
    
    func (r *SomeRepository) Get(id string) (*SomeModel, error) {
        // Handling a real repository access and returning your Object
    }
    

    When you need to mock it, just create a Mock-Struct and implement the interface:

    // repository_test.go
    
    type SomeMockRepository struct { ... }
    
    func (r *SomeRepository) Get(id string) (*SomeModel, error) {
        return &SomeModel{...}, nil
    }
    
    func TestSomething() {
        // You can use your mock as ISomeRepository
        var repo *ISomeRepository
        repo = &SomeMockRepository{}
        someModel, err := repo.Get("123")
    }
    

    This is best used with some kind of dependency-injection, so passing this repository as ISomeRepository into the function.

    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画