dsf5632
2015-11-29 05:08
浏览 131

Golang MongoDb GridFs测试

I have a rest API implemented using Gorilla Mux in Golang. This API uploads/downloads files from MongoDb GridFs. I want to write integration tests for my API.
Is there a embedded MongoDb package with GridFs support in Go? How do we test APIs using GridFs? Do we need to test against a real MongoDB?
Java seems to have such a library

As part of the test, I would like to start embedded MongoDB and stop it at the end of the test.

图片转代码服务由CSDN问答提供 功能建议

我在Golang中使用Gorilla Mux实现了REST API。 该API从MongoDb GridFs上传/下载文件。 我想为我的API编写集成测试。
Go中是否有一个带有 GridFs支持嵌入式MongoDb 包? 我们如何使用GridF测试API?
Java似乎具有这样的

作为测试的一部分,我想启动嵌入式MongoDB并在测试结束时将其停止。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doutenglou6588 2015-11-29 12:36
    已采纳

    There is no embedded MongoDB for Go as far as I am aware of.

    What I do is to use mgo's own gopkg.in/mgo.v2/dbtest which you can install as usual with

    go get -u "gopkg.in/mgo.v2/dbtest"
    

    Although it requires a mongod inside your $PATH, the dbtest takes care of all the rest.

    You get a server with

    package StackOverflowTests
    
    import (
      "io/ioutil"
      "os"
      "testing"
    
      "gopkg.in/mgo.v2/dbtest"
    )
    
    func TestFoo(t *testing.T) {
    
        d, _ := ioutil.TempDir(os.TempDir(), "mongotools-test")
    
        server := dbtest.DBServer{}
        server.SetPath(d)
    
        // Note that the server will be started automagically
        session := server.Session()
    
        // Insert data programmatically as needed
        setupDatabaseAndCollections(session)
    
        // Do your testing stuff
        foo.Bar(session)
        // Whatever tests you do
    
        // We can not use "defer session.Close()" because...
        session.Close()
    
        // ... "server.Wipe()" will panic if there are still connections open
        // for example because you did a .Copy() on the
        // original session in your code. VERY useful!
        server.Wipe()
    
        // Tear down the server
        server.Stop()
    }
    

    Note that you neither have to define an IP or port, which are provided automagically (a free open port in the non-reserved range of localhost is used).

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题