英文:
Golang MongoDb GridFs Testing
问题
我使用Golang中的Gorilla Mux实现了一个REST API。该API可以上传/下载MongoDb GridFs中的文件。我想为我的API编写集成测试。是否有一个带有GridFs支持的嵌入式MongoDb
包在Go中?我们如何使用GridFs测试API?我们需要对真实的MongoDB进行测试吗?
Java似乎有一个名为library
的库(https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo)。
作为测试的一部分,我想启动嵌入式MongoDB,并在测试结束时停止它。
英文:
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. <br>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?
<br>
Java seems to have such a <a href="https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo">library</a>
As part of the test, I would like to start embedded MongoDB and stop it at the end of the test.
答案1
得分: 3
据我所知,Go语言中没有内置的MongoDB。我通常使用mgo的gopkg.in/mgo.v2/dbtest来进行测试,你可以像平常一样使用以下命令安装:
go get -u "gopkg.in/mgo.v2/dbtest"
虽然它需要在$PATH中有mongod
,但dbtest会处理其余的事情。
你可以通过以下代码获取一个服务器:
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)
// 注意,服务器将自动启动
session := server.Session()
// 根据需要以编程方式插入数据
setupDatabaseAndCollections(session)
// 进行测试
foo.Bar(session)
// 进行其他测试
// 由于...
session.Close()
// ...如果仍然有连接打开,"server.Wipe()"将引发panic
// 例如,因为你在代码中对原始session进行了.Copy()。非常有用!
server.Wipe()
// 关闭服务器
server.Stop()
}
请注意,你不需要定义IP或端口,它们会自动提供(在本地主机的非保留范围内使用一个免费开放端口)。
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论