配置&使用 mongodb 模型服务器进行单元测试
我必须使用 MongoDB 存储为 Java 代码开发一些 Junit 测试。是否有任何框架/库允许我初始化模拟内存 MongoDB 服务器?
(这个想法是只测试代码本身,这意味着,在任何机器上独立测试 MongoDB 是否安装和运行)。
提前致谢!
I have to develop some Junit tests for Java code using a MongoDB store. Is there any framework/library which permits me initializing a mock in-memory MongoDB server?
(The idea is to test only the code itself, that means, in any machine independently on if MongoDB is installed & running).
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
fongo 可能就是您要找的。
fongo might be what you are looking for.
我用 Java 编写了一个 MongoDB 假实现: mongo-java-server (参见 这个答案)。
I wrote a MongoDB fake implementation in Java: mongo-java-server (see this answer).
我们实际上正在研究这样一个测试系统,而且它是相当可行的。在我们的方法中,我们的测试框架扩展了标准测试用例类(在我们的例子中是 JUnit,但 TestNG 似乎更有能力),它使用以下步骤设置和拆除每个测试的各种数据库依赖项:
测试套件设置
1)启动 mongod 进程(我们使用 ProcessBuilder,存储 Process 实例)
测试设置:
2)使用特定于测试的 .js 文件运行 mongo 以生成初始数据状态
测试
3)运行测试
测试拆卸
4)删除数据库
测试套件拆卸
5)停止mongod 进程 (process.destroy())
由于启动和停止 mongod 是唯一耗时的事情,我强烈建议尽可能少地这样做。最好对整个测试套件进行一次。我们的工作尚未完成,但早期结果是积极的。我认为没有很多替代方案可用。在撰写本文时,没有可用的 mongo 模拟库,并且 mongod 没有内存/嵌入模式。
We're actually working on such a test system and it's quite feasible. In our approach our test framework extends the standard test case class (JUnit in our case but TestNG seems more capable) that sets up and tears down the various database dependecies with each test using the following steps :
Test Suite Setup
1) Start mongod process (we use ProcessBuilder, store Process instance)
Test Setup :
2) Run mongo with a test specific .js file to produce initial data state
Test
3) Run test
Test Teardown
4) Drop database
Test Suite Teardown
5) Stop mongod process (process.destroy())
Since starting and stopping mongod is the only time consuming thing i'd strongly suggest doing this as little as possible. Preferably once for the entire test suite. Our stuff isn't finished yet but early results are positive. I don't think many alternatives are available. No mongo mock library is available at time of writing and mongod does not have a in-memory/embedded mode.
事实并非如此,您必须自己在应用程序层中执行此类操作。如果您使用 Morphia,您可以将任何模拟框架与您喜欢的服务层一起使用(因为对象只是 POJO),但在 db/driver 级别没有任何东西可以帮助您。
许多人只使用本地开发人员。 mongodb 实例带有一组测试数据,因为它太快了。我知道有人为每个测试加载测试数据,例如用假/测试数据复制数据库。
Not really, you have to do that kind of thing yourself in your application layers. If you use Morphia you can use any mock framework with your service layers you like (since the objects are just POJOs), but there is nothing at the db/driver level to help you out.
Many people just use a local dev. mongodb instance with a set of test data since it is so fast. I know of people who load test data for each test, like copying a database with fake/test data.
作为测试装置设置的一部分,删除数据库并用任何默认测试数据填充它。
As part of your test fixture setup, drop the database and populate it with any default test data.