问题

我的问题是this one的变种。

由于我的Java Web应用程序项目需要大量读取过滤器/查询以及与GridFS等工具的接口,因此我很难想出以上述解决方案建议的方式使用MongoDB的合理方法。

因此,我正在考虑在我的集成测试中运行MongoDB的嵌入式实例。我想它以自动启动(无论是每个测试还是整个套件),刷新数据库进行每次测试,并且关闭结束。这些测试可能在开发机器和CI服务器上运行,因此我的解决方案也需要beportable

任何对MongoDB有更多了解的人都可以帮助我了解这种方法的可行性,并且/或者建议任何可能帮助我入门的阅读材料吗?

我也对人们对如何解决这个问题的其他建议持开放态度......


#1 热门回答(89 赞)

我找到了Embedded MongoDBlibrary,看起来非常有前途,并且做了你要求的。

目前支持MongoDB版本:1.6.5to3.1.6,前提是二进制文件仍可从配置的镜像中获得。

这是一个简短的使用示例,我刚刚尝试过,它完美地运行:

public class EmbeddedMongoTest {
    private static final String DATABASE_NAME = "embedded";

    private MongodExecutable mongodExe;
    private MongodProcess mongod;
    private Mongo mongo;

    @Before
    public void beforeEach() throws Exception {
        MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
        mongodExe = runtime.prepare(new MongodConfig(Version.V2_3_0, 12345, Network.localhostIsIPv6()));
        mongod = mongodExe.start();
        mongo = new Mongo("localhost", 12345);
    }

    @After
    public void afterEach() throws Exception {
        if (this.mongod != null) {
            this.mongod.stop();
            this.mongodExe.stop();
        }
    }

    @Test
    public void shouldCreateNewObjectInEmbeddedMongoDb() {
        // given
        DB db = mongo.getDB(DATABASE_NAME);
        DBCollection col = db.createCollection("testCollection", new BasicDBObject());

        // when
        col.save(new BasicDBObject("testDoc", new Date()));

        // then
        assertThat(col.getCount(), Matchers.is(1L));
    }
}

#2 热门回答(17 赞)

有Foursquare产品560886498。 Fongo是mongo的内存中java实现。它拦截对标准mongo-java-driver的调用,用于查找,更新,插入,删除和其他方法。主要用于轻量级单元测试,你不希望启动mongo进程。


#3 热门回答(7 赞)

如果你使用的是sbt和specs2,我为embedmongo编写了相同类型的包装器
https://github.com/athieriot/specs2-embedmongo


原文链接