Golang MongoDb GridFs 测试
Golang MongoDb GridFs Testing
我有一个休息 API 在 Golang 中使用 Gorilla Mux 实现。此 API uploads/downloads 个文件来自 MongoDb 个 GridFs。我想为我的 API 编写集成测试。
Go 中有 embedded MongoDb
包 GridFs support
吗?我们如何使用 GridFs 测试 APIs?我们需要针对真实的 MongoDB 进行测试吗?
Java好像有这么一个library
作为测试的一部分,我想开始嵌入 MongoDB 并在测试结束时停止它。
据我所知,Go 没有嵌入式 MongoDB。
我所做的是使用 mgo 自己的 gopkg.in/mgo.v2/dbtest,您可以像往常一样安装
go get -u "gopkg.in/mgo.v2/dbtest"
虽然它需要在您的 $PATH 中使用 mongod
,但 dbtest 会处理所有其余的事情。
你得到一个服务器
package WhosebugTests
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()
}
请注意,您不必定义自动提供的 IP 或端口(使用 localhost 非保留范围内的空闲开放端口)。
我有一个休息 API 在 Golang 中使用 Gorilla Mux 实现。此 API uploads/downloads 个文件来自 MongoDb 个 GridFs。我想为我的 API 编写集成测试。
Go 中有 embedded MongoDb
包 GridFs support
吗?我们如何使用 GridFs 测试 APIs?我们需要针对真实的 MongoDB 进行测试吗?
Java好像有这么一个library
作为测试的一部分,我想开始嵌入 MongoDB 并在测试结束时停止它。
据我所知,Go 没有嵌入式 MongoDB。
我所做的是使用 mgo 自己的 gopkg.in/mgo.v2/dbtest,您可以像往常一样安装
go get -u "gopkg.in/mgo.v2/dbtest"
虽然它需要在您的 $PATH 中使用 mongod
,但 dbtest 会处理所有其余的事情。
你得到一个服务器
package WhosebugTests
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()
}
请注意,您不必定义自动提供的 IP 或端口(使用 localhost 非保留范围内的空闲开放端口)。