Is there a DbUnit alternative that works with MongoDB? Is there a DbUnit alternative that works with MongoDB? mongodb mongodb

Is there a DbUnit alternative that works with MongoDB?


EmbedMongo is a great tool to use for that. And it integrates with Maven.

EmbedMongo allows you to easily setup an embedded MongoDB instance for test. It has in-built clean up support once tests complete.

See this tutorial. http://blog.yohanliyanage.com/2012/11/integration-testing-mongodb-spring-data/


Here is simple but a little raw util which can set db state to described in json: https://github.com/kirilldev/mongomery

To load database state you need write only two lines of code:

//db here is a com.mongodb.DB instanceMongoDBTester mongoDBTester = new MongoDBTester(db);mongoDBTester.setDBState("predefinedTestData.json");

To check db state:

mongoDBTester.assertDBStateEquals("expectedTestData.json");

There is two ways to write json files with expected data:

Strict match. This is usual json file wich represents db state. In most cases you don't need more than exact describing of db state after test.

Pattern match. If you want to use random strings in your test or for example your business logic generates random ids for entities you may want a little more than strict match:

{ "Movies": [ { "_id": "$anyObject()", "name": "Titanic", "year": 1997 } ] }

json above says that test expects one document in "Movies" collection that will have name Titanic and a year 1997. Also it must have non null field _id with any object in it.


You could always use mongodump/mongoimport/mongorestore if you don't mind exec'ing out. Or you could use a file of json documents and use com.mongodb.util.JSON#parse() or jackson to read that json in to DBObjects and write those out to mongo.