Search code examples
mongodbgomgo

Golang MongoDb GridFs Testing


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.


Solution

  • 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).